簡體   English   中英

我怎么能在 javascript 中做 Promise ?

[英]How can i do Promise all in javascript?

I have used Promise.all and I'm not getting a single promise at the end but promise should accept a bunch of individual promises and gives you back a single promise right?

我有一個 for 循環,它將調用一個異步執行操作的方法。 這個循環可以多次調用該方法。 在這個循環之后,我有另一個循環,只有在所有東西都完成后才需要執行。

function doSomethingAsync(i) {
// do your stuf 
    setValue(i, function(err, result) {
        if (err) {
            console.log(err)
        } else {
            console.log(result)
        }
    })
}

有人可以在這里幫助我。我不確定我的實現是否正確。

您的 function doSomethingAsync不返回任何承諾。 相反,它使用回調。 你可以像這樣包裹它。

function doSomethingAsync(i) {
// do your stuf 
    return new Promise(resolve => {
        setValue(i, function(err, result) {
        if (err) {
            console.log(err);
            resolve(err);
        } else {
            console.log(result);
            resolve(result);
        }
    })
    })
}

暫無
暫無

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

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