【发布时间】:2018-02-14 03:34:45
【问题描述】:
我有以下使用 fetch 的代码。据我了解,在履行承诺之前不会调用回调函数。因此,我期望回调函数在处理其他事情(例如 for 循环)的过程中执行。但是,它并没有达到我的预期。我的代码如下:
console.log("Before fetch")
fetch('https://example.com/data')
.then(function(response){
console.log("In first then")
return response.json()
})
.then(function(json){
console.log("In second then")
console.log(json)
})
.catch(function(error){
console.log("An error has occured")
console.log(error)
})
console.log("After fetch")
for(let i = 0; i < 1000000; i++){
if (i % 10000 == 0)
console.log(i)
}
console.log("The End")
不是在实现承诺时立即运行回调,而是在激活回调函数之前等待我的所有其余代码处理完毕。这是为什么呢?
我的代码输出如下所示:
Before fetch
After fetch
0
10000
.
.
.
970000
980000
990000
The End
In first then
In second then
但是,我预计最后两行会出现在此之前的某个地方。这里发生了什么?如何更改我的代码以反映实际兑现承诺的时间?
【问题讨论】:
-
1M 操作对于现在的 CPU 来说不算什么,你确定你的请求只需要很少的时间吗(这里以毫秒为单位)。
-
你指的是哪个回调?也许我遗漏了一些东西,但是在您的代码中,for 循环与您的承诺链是分开的......正如@NiVeR 所说,它似乎工作正常。
-
fetch.whatever 之后的所有内容。将在 fetch 开始后立即运行。 then 和 catch 块与你的 for 循环并行运行
-
您可以使用
async/await强制执行任务的顺序 -
我还建议观看这个关于事件循环的精彩解释youtube.com/watch?v=8aGhZQkoFbQ
标签: javascript callback promise