Ecmascript 6 依次取回
代码如下:Ecmascript 6 依次取回,ecmascript-6,fetch,Ecmascript 6,Fetch,代码如下: var fetch = require('node-fetch') function fetchA(){ fetch('https://github.com/keegoo') .then(response => console.log('fetchA')) .then(fetchB) .then(fetchC) .then(() => console.log('hi')) } function fetchB(){ fetch('
var fetch = require('node-fetch')
function fetchA(){
fetch('https://github.com/keegoo')
.then(response => console.log('fetchA'))
.then(fetchB)
.then(fetchC)
.then(() => console.log('hi'))
}
function fetchB(){
fetch('https://github.com/keegoo/trigger')
.then(response => console.log('fetchB'))
}
function fetchC(){
fetch('https://github.com/keegoo/trigger/tree/master/app')
.then(response => console.log('fetchC'))
}
// call
fetchA()
在fetchA内部,我调用了fetchB和fetchC
我希望输出应该是:
fetchA
fetchB
fetchC
hi
相反,它是:
fetchA
hi
fetchC
fetchB
为什么?
如果我需要输出为fetchA->fetchB->fetchC->Hi,我该怎么办?您的fetchB和fetchC应该返回fetch的承诺,否则后续的调用,如。然后fetchB会立即得到解决
function fetchB(){
return fetch('https://github.com/keegoo/trigger')
.then(response => console.log('fetchB'))
}
function fetchC(){
return fetch('https://github.com/keegoo/trigger/tree/master/app')
.then(response => console.log('fetchC'))
}
你需要回报承诺
在理解原因之前,你需要知道以下两个事实
此处承诺人的返回值将传递给下一个承诺人。
答应我,解决“A”
.thenx=>{
console.logx//输出A
返回“B”
}
.thenx=>{
console.logx//输出B
//这里不归!
}
.thenx=>{
console.logx//输出未定义,因为**previous**`then`没有返回任何内容
返回“C”
}
.thenx=>{
console.logx//输出C
返回'D'
}//承诺链继续…您仍然没有返回通过调用fetch生成的承诺。fetch与React无关:。@KevinB和@Sheng,我知道如果没有此返回fetch…,它将立即解决。但为什么有了它,一切都不同了?它是如何在内部处理此返回的。然后?@mCY:。然后返回一个承诺a。该承诺将解析为传递给它的回调的返回值(如果该值是正常值)。但如果该值是另一个承诺B,则承诺A将链接到承诺B,解析为B解析为的任何内容。@mCY fetch函数返回承诺,因为它是异步请求。谢谢,这真的很有帮助!