簡體   English   中英

Javascript 承諾,所有的 .then 同時執行

[英]Javascript promise, all the .then execute at the same time

此時.then之后的所有console.log,同時執行。 我希望每個 .then 等待前一個,我該怎么做?

function doIt(sentence) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(console.log(sentence))
        }, 2000)
    })
}

doIt('Place order')
    .then(() => setTimeout(() => { console.log('Cut the fruit') }, 2000))
    .then(() => setTimeout(() => { console.log('Add water and ice') }, 2000))
    .then(() => setTimeout(() => { console.log('Start the machine') }, 2000))
    .then(() => setTimeout(() => { console.log('Select topping') }, 2000))
    .then(() => setTimeout(() => { console.log('Serve the ice cream') }, 2000))

你必須創建一個承諾鏈。

 function doIt(sentence) { return new Promise((resolve, reject) => { setTimeout(() => resolve(console.log(sentence)), 2000); }); } doIt("Place order") .then(() => doIt("Cut the fruit")) .then(() => doIt("Add water and ice")) .then(() => doIt("Start the machine")) .then(() => doIt("Select topping")) .then(() => doIt("Serve the ice cream"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM