簡體   English   中英

Promise.all 中的回調

[英]Callback inside Promise.all

我對使用 Promise.all 有疑問。 我需要三個帶回調的函數。 所以我將這三個函數寫在 Promise.all 中,然后在 Promise.all 的 .then() 中獲取所有三個函數結果。 這是正確的方法還是有其他方法?

聽起來你做對了,是的; 如果你能展示代碼就更好了。

但是假設您要啟動三個進程,它們由doThis()doThat()doTheOther() 你這樣處理:

Promise.all([
    doThis(),
    doThat(),
    doTheOther()
])
.then(([thisResult, thatResult, theOtherResult]) => { // The destructuring is optional, of course
    // ...use them...
})
.catch(error => {
    // ...handle/report error...
});

關鍵位:

  1. 您將一個可迭代Promise.all傳遞給Promise.all (我在上面使用了一個數組)
  2. 您以與可迭代相同的順序收到結果(無論完成的順序如何)
  3. 如果任何操作拒絕, Promise.all的承諾將拒絕。

在您發布此代碼的評論中:

Promise.all([
    client.query(q1,function(err,res){ dosomething();}),
    client.query(q2,function(err,res){ dosomething();})
])
.then(() => {
    dosomething()};
})  // <== Added missing }
.catch(e => {
    console.log(e); // <== Added missing ;
}); // <== Added missing ;

那看起來不正確。 通常,當一個函數像你展示的query那樣接受回調時,它不會返回一個承諾。 檢查您正在進行的query調用的文檔。

如果它返回一個承諾,那么你可以像這樣使用它:

Promise.all([
    client.query(q1).then(dosomething),
    client.query(q2).then(dosomething)
])
.then(() => {
    dosomething()};
})  // <== Added missing }
.catch(e => {
    console.log(e); // <== Added missing ;
}); // <== Added missing ;

...假設您希望僅在查詢成功時調用doSomething (無論查詢成功還是失敗,您的代碼都會調用它)。

如果query沒有返回承諾,你會將它包裝在一些可以返回的東西中,如下所示:

function doQuery(client, q) {
    return new Promise((resolve, reject) => {
        client.query(q, function(err, res) {
            if (err) {
                reject(err);
            } else {
                resolve(res);
            }
        });
    });
}

然后使用:

Promise.all([
    doQuery(client, q1).then(doSomething),
    doQuery(client, q2).then(doSomething)
])
.then(() => {
    dosomething()};
})  // <== Added missing }
.catch(e => {
    console.log(e); // <== Added missing ;
}); // <== Added missing ;

(同樣,我假設doSomething應該只在查詢成功時調用。)

如今,許多 API 都在添加承諾功能。 此外,還有util.promisify用於在util.promisify中包裝回調風格的 API 函數。 這是您將其與代碼一起使用的方式

const doQuery = util.promisify(client.query.bind(client)); // Note the .bind(client)
Promise.all([
    doQuery(q1).then(doSomething),
    doQuery(q2).then(doSomething)
])
.then(() => {
    dosomething()};
})  // <== Added missing }
.catch(e => {
    console.log(e); // <== Added missing ;
}); // <== Added missing ;

您需要將回調包裝在一個承諾中,以使用 Promise.all 解決它們

所以:

Promise.all([
    new Promise(resolve => client.query(q1, function(err, result) { resolve(result); }) ),
    new Promise(resolve => client.query(q2, function(err, result) { resolve(result); }) ),
    new Promise(resolve => client.query(q3, function(err, result) { resolve(result); }) )
]).then(([q1, q2, q3]) => {
   //do something with results
}).

如果您需要處理錯誤,則需要拒絕錯誤。

希望有幫助。

暫無
暫無

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

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