问题描述
我一直在玩Promises,但我无法理解以下代码所发生的事情:
I have been playing with Promises, but I am having trouble understanding what is happening with the following code:
function a() {
return new Promise(function (resolve, reject) {
resolve("hi from a!");
});
}
function b() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("hi from b!");
}, 5000);
});
}
function c() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("hi from c!");
}, 1000);
});
}
a().then(function (resultFromA) {
console.log("a() responded with: " + resultFromA);
b();
}).then(function (resultFromB) {
console.log("b() responded with: " + resultFromB);
c();
}).then(function (resultFromC) {
console.log("c() responded with: " + resultFromC);
});
我希望输出 a()回复:hi来自a !
立即与 b()一起回复:hi来自b!
和 c()回复:hi from c!
在各自的 setTimeout()
之后触发。但是,我立即得到以下输出:
I am expecting this to output a() responded with: hi from a!
immediately, along with b() responded with: hi from b!
and c() responded with: hi from c!
after their respective setTimeout()
fires. However, what I get this the following output immediately:
b()回复:未定义
c()回复:undefined
c() responded with: undefined
我以为 .then()
等待这些承诺,但事实并非如此。任何帮助将不胜感激。
I was thinking that .then()
waits on these promises, but it isn't. Any help would be appreciated.
推荐答案
您需要返回b()
和从
。然后
处理程序中返回c()
You need to return b()
and return c()
from within your then
handlers.
然后
仅替换第一个承诺,后续承诺从其回调返回。
then
only "replaces" the first promise with a subsequent promise which is returned from its callback.
如果你的然后
回调不是返回
一个承诺,那么然后
适用于原始承诺,无论先前然后
回调的内容/结果如何,它都会立即执行。
If your then
callback doesn't return
a promise, then the then
applies to the original promise, and it will be executed immediately regardless of the contents/result of the previous then
callback.
基本上......
a().then(function () {
b()
}).then( # This "then" is chained off of a's promise
反过来说:
a().then(function () {
return b()
}).then( # This "then" is chained off of b's promise
这篇关于JavaScript Promises和setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!