簡體   English   中英

如何在Javascript的forEach循環中正確鏈接Promise

[英]How to properly chain promises inside of a forEach loop in Javascript

我正在使用mongo,需要對循環內的每個項目進行異步調用。 我想在循環中的所有promise完成后執行另一個命令,但是到目前為止,循環中的promise似乎在循環中的代碼之后完成了。

本質上,我希望訂單能夠

循環答應其他代碼

而不是現在是什么

其他代碼循環承諾

 MongoClient.connect(connecturl) .then((client) => { databases.forEach((val) => { val.collection.forEach((valcol) => { client.db(val.databasename).stats() //(This is the async call) .then((stats) => { //Do stuff here with the stats of each collection }) }) }) }) .then(() => { //Do this stuff after everything is finished above this line }) .catch((error) => { } 

任何幫助將不勝感激。

假設您正在使用.forEach()的東西是可迭代的(數組或類似的東西),則可以使用async/await序列化一個for/of循環:

    MongoClient.connect(connecturl).then(async (client) => {
        for (let db of databases) {
            for (let valcol of db.collection) {
                let stats = await client.db(db.databasename).stats();
                // Do stuff here with the stats of each collection
            }
        }
    }).then(() => {
        // Do this stuff after everything is finished above this line
    }).catch((error) => {
        // process error
    })

如果您想堅持使用.forEach()循環,則可以通過並行執行並使用Promise.all()知道何時完成操作來使其全部工作:

MongoClient.connect(connecturl).then((client) => {
    let promises = [];
    databases.forEach((val) => {
        val.collection.forEach((valcol) => {
            let p = client.db(val.databasename).stats().then((stats) => {
                // Do stuff here with the stats of each collection
            });
            promises.push(p);
        }); 
    });
    return Promise.all(promises);
}).then(() => {
    // Do this stuff after everything is finished above this line
}).catch((error) => {
    // process error here
});

暫無
暫無

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

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