JavaScript Promises and setTimeout

JavaScript Promises and setTimeout

本文关键字:setTimeout and Promises JavaScript      更新时间:2024-03-12

我一直在玩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()回应道:你好!

b()响应为:未定义

c()响应为:未定义

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

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

then仅用后续promise"替换"第一个promise,该后续promise从其回调中返回

如果您的then回调没有将return作为promise,那么then将应用于原始promise,并且无论上一次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);
});

您忘记了从函数调用返回。Javascript函数不会隐式返回。

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);
});