JavaScript 承诺和 setTimeout

JavaScript Promises and setTimeout

我一直在玩 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);
});

我期待它在各自的 setTimeout() 触发后立即输出 a() responded with: hi from a!,以及 b() responded with: hi from b!c() responded with: hi from c!。但是,我立即得到以下输出:

a() responded with: hi from a!

b() responded with: undefined

c() responded with: undefined

我原以为 .then() 会等待这些承诺,但事实并非如此。任何帮助将不胜感激。

您需要从 then 处理程序中 return b()return c()

then 仅 "replaces" 第一个 promise 和后续 promise 从回调中返回

如果您的 then 回调没有 return 承诺,那么 then 将应用于原始承诺,并且无论 contents/result 之前的 then 回调。

基本上...

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

您需要 return promises 链接它们:

a().then(function (resultFromA) {
  console.log("a() responded with: " + resultFromA);
  // return b() promise
  return b();
}).then(function (resultFromB) { 
  console.log("b() responded with: " + resultFromB);
  // return c() promise
  return c();
}).then(function (resultFromC) { 
  console.log("c() responded with: " + resultFromC);
});

您忘记从函数调用中 return。 Javascript 函数不会 return 隐含地。

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);
    return b(); // return 
}).then(function (resultFromB) { 
    console.log("b() responded with: " + resultFromB);
    return c(); // return
}).then(function (resultFromC) { 
    console.log("c() responded with: " + resultFromC);
});