[英]JavaScript: Promise.All() and Async / Await and Map()
我試圖理解為什么以下兩個代碼塊會產生不同的結果。
第一個代碼塊按預期工作,並返回從數據庫中查找的提供程序數組。 另一方面,代碼塊二返回一個函數數組。 我覺得我在理解 Promise.all() 和 async/await 時缺少一些簡單的東西。
代碼塊的區別是:
第 1 塊:創建 promise 函數數組,然后使用 map 運算符將其包裝在異步函數中。
第 2 塊:將 promise 函數數組創建為異步函數。 因此,不會調用 map 運算符。
如果您不熟悉 Sequelize 庫,被調用的 findOne() 方法會返回一個 promise。
另外值得一提的是,我知道我可以使用帶有“name in” where 子句的單個 find 查詢來獲得相同的結果,而無需為多個選擇查詢創建一組 promise。 我這樣做只是作為 async/await 和 Promise.all() 的學習練習。
代碼塊 1:在 Promise.all() 中使用 map()
private async createProfilePromises(profiles){
let profileProviderFindPromises = [];
//Build the Profile Providers Promises Array.
profiles.forEach(profile => {
profileProviderFindPromises.push(
() => {
return BaseRoute.db.models.ProfileProvider.findOne({
where: {
name: {[BaseRoute.Op.eq]: profile.profileProvider}
}
})}
);
});
//Map and Execute the Promises
let providers = await Promise.all(profileProviderFindPromises.map(async (myPromise) =>{
try{
return await myPromise();
}catch(err){
return err.toString();
}
}));
//Log the Results
console.log(providers);
}
代碼塊 2:在不使用 map() 的情況下添加異步函數
private async createProfilePromises(profiles){
let profileProviderFindPromises = [];
//Build the Profile Providers Promises Array.
profiles.forEach(profile => {
profileProviderFindPromises.push(
async () => {
try{
return await BaseRoute.db.models.ProfileProvider.findOne({
where: {
name: {[BaseRoute.Op.eq]: profile.profileProvider}
}
});
}catch(e){
return e.toString();
}
}
);
});
//Execute the Promises
let providers = await Promise.all(profileProviderFindPromises);
//Log the Results
console.log(providers);
}
您的代碼基本上歸結為:
const array = [1, 2, 3];
function fn() { return 1; }
array.map(fn); // [1, 1, 1]
array.push(fn);
console.log(array); // [1, 2, 3, fn]
您推送一個函數(是否async
無關緊要),而是希望推送調用該函數的結果:
array.push(fn());
或者在你的情況下:
array.push((async () => { /*...*/ })());
我將如何編寫您的代碼:
return Promise.all(profiles.map(async profile => {
try{
return await BaseRoute.db.models.ProfileProvider.findOne({
where: {
name: { [BaseRoute.Op.eq]: profile.profileProvider }
}
});
} catch(e) {
// seriously: does that make sense? :
return e.toString();
}
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.