[英]How can i synchronize these 3 promise-based functions?
我如何同步這 3 個承諾返回函數(例如在其他函數中)? 我想獲得以下輸出 -> 開始 -> (2secs)..2..(3secs)..3..(4secs)..4 -> End。 我試過發電機,但我的輸出不是那樣的(可能我做錯了什么)
function resolveAfter2Seconds() {
new Promise(resolve => {
setTimeout(() => {
resolve('resolved 2');
console.log('2')
}, 2000);
});
}
function resolveAfter3Seconds() {
new Promise(resolve => {
setTimeout(() => {
resolve('resolved 2');
console.log('3')
}, 3000);
});
}
function resolveAfter4Seconds() {
new Promise(resolve => {
setTimeout(() => {
resolve('resolved 2');
console.log('4')
}, 4000);
});
}
首先,更改函數以返回其承諾。 例如:
function resolveAfter2Seconds() {
return new Promise(resolve => { // <------ added return statement
setTimeout(() => {
resolve('resolved 2');
console.log('2')
}, 2000);
});
}
然后要么將承諾鏈接在一起
resolveAfter2Seconds()
.then(() => resolveAfter3Seconds())
.then(() => resolveAfter4Seconds());
或者使用 async/await 語法:
async function exampleFunction() {
await resolveAfter2Seconds();
await resolveAfter3Seconds();
await resolveAfter4Seconds();
}
您可能想嘗試鏈接以獲得順序輸出:
resolveAfter2Seconds()
.then(() => resolveAfter3Seconds())
.then(() => resolveAfter4Seconds())
附注。 不要忘記讓這些函數返回承諾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.