簡體   English   中英

Promise.promise的所有數組

[英]Promise.all array of promises

我有以下代碼:

 db.group.findOne({_id: id}).then((groupFound) => {
     var membersArray = groupFound.members;

     Promise.all(membersArray.map((member) => {
         return db 
            .doneTodo
            .find({'victor._id': member._id})
            .then((userVictories) => {
                return {
                    email: member.email,
                    victories: userVictories.length
                }
            });
    })).then(function (result) {
        console.log(result);
    });

數據庫調用都是MongoDB / Mongoose。

map函數返回的數組內部是所有promise。

最后一個電話:

.then((userVictories) => {
    return {
        email: member.email,
        victories: userVictories.length
    }
})

返回承諾。

因此,從本質上講,在進行此調用后,我得到的是:

[promise1, promise2, promise3, ... , promise x]

這些諾言如何得出結論以將數組值更改為promise1.then( (result))

如何完成這些承諾以將數組值更改為promise1.then((result))的值?

這里沒什么特別的。 數組中的promise會像任何promise一樣起作用-它們將在一段時間后解析為某個值,在一段時間后導致錯誤,或者如果它們的設置不正確,則永遠不要解析或產生錯誤。

Promise.all的目的僅僅是等待數組中的所有值解析或拋出一個錯誤。 如果它們全部解決,則Promise.all返回的Promise.all將解析為所有結果的數組。 如果有人拋出錯誤,它將產生該錯誤。

Promise.all對承諾沒有做任何事情 ,只是在遵守它們。 我們可以創建自己的Promise.all版本,就像這樣:

 function myAll(arr) { var resolvedCount = 0; var resultArray = []; return new Promise(function (resolve, reject) { if (arr.length === 0) { resolve([]); } arr.forEach(function (el, i) { // wrap el in a promise in case it's not already one Promise.resolve(el) .then( function (result) { // add result to the result array and increment the count resultArray[i] = result; resolvedCount += 1; if (resolvedCount === arr.length) { // all promises have resolved, // so this promise can resolve itself resolve(resultArray); } }, function (err) { // a promise threw an error. reject reject(err); } ); // end of .then() }); // end of .forEach() }); // end of new Promise() } // test out myAll() function log(value) { console.log(value); } function logError(value) { log('Error caught:' + value); } myAll([]) .then(log, logError); myAll([1, Promise.resolve('apple'), 5, Promise.resolve(7)]) .then(log, logError); myAll([2, 3, Promise.reject('no!')]) .then(log, logError); 

暫無
暫無

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

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