【发布时间】:2016-04-08 03:02:28
【问题描述】:
我一直在玩 Promises,但我无法理解以下代码发生了什么:
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() responded with: hi from a!,以及b() responded with: hi from b! 和c() responded with: hi from c! 在各自的setTimeout() 触发后。但是,我立即得到以下输出:
a() 回复:hi from a!
b() 回应:未定义
c() 回应:未定义
我在想.then() 会等待这些承诺,但事实并非如此。任何帮助将不胜感激。
【问题讨论】: