[英]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);
});
我期待這個輸出a() responded with: hi from a!
馬上,與b() responded with: hi from b!
並且c() responded with: hi from c!
在各自的setTimeout()
觸發后。 但是,我立即獲得以下輸出:
a()回復:嗨來自!
b()回復:undefined
c()回復:undefined
我在想.then()
會等待這些承諾,但事實並非如此。 任何幫助,將不勝感激。
您需要return b()
並從then
處理程序中return c()
。
then
只用從其回調返回的后續承諾“替換”第一個承諾。
如果你then
回調不return
一個承諾,然后then
應用到原來的承諾,將立即不管前面的內容/結果的執行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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.