[英]Node.js - Wait for multiple async calls to finish before continuing in code
[英]NodeJS - How to wait for multiple Async calls to finish before continuing execution flow?
我有一个 function getAliasesByRoleDetailed(role)
负责获取给定role
的用户数据(此 function 使用 Z38C3787939C7B0B6C17D73FCE3D28 来获取数据)。
这个 function 的 output 是这样的:
[
{
alias: 'xxxx',
Role: 'Admin',
grantedBy: 'rnfnf',
timestamp: '1591375676333'
},
{
alias: 'vbjp',
Role: 'Admin',
'Granted By': 'hjkds',
timestamp: '1588013678236'
}
]
可以这样做:
const response = await getAliasesByRoleDetailed(role);
然后在数据可用后继续进行response
。
但是,如果我想在继续执行代码之前多次调用这个getAliasesByRoleDetailed(role)
function 和.push()
将结果放入一个数组中怎么办?
['Admin','Trainer','Manager']
这样的数组中的每个元素执行getAliasesByRoleDetailed(role)
并将每次执行的结果推送到resultsArray
中。resultsArray
中可用之后,我想继续我的逻辑,使用resultsArray
数据。所以,理想情况下:
//Inside a function...
[getting data using getAliasesByRoleDetailed(role) ...]
resultsArray.forEach( (e) => {
//Do something useful with all these element I now have!
}
我用 async/await 和.forEach()
尝试了几个解决方案,但一直卡住。 有一个简单的解决方案吗?
如果我正确理解您的问题,您可能想使用Promise.all
。
这将等待所有内部承诺(传递给函数的承诺)在自行解决之前解决。
// inside an async function
const roles = ['Admin', 'Trainer', 'Manager'];
const results = await Promise.all(roles.map(role => {
return getAliasesByRoleDetailed(role);
}));
// results should now have all the results available
然后,您可以使用Array.flat
展平阵列
// inside the same function
const flattenResults = Array.flat(results);
既然你提到了异步/等待,我假设getAliasesByRoleDetailed
返回一个Promise
。 因此,你必须做类似的事情
let resultsArray = await Promise.all(['Admin','Trainer','Manager'].map(getAliasesByRoleDetailed))
let result = await data.reduce(async (promise, value) => {
await promise;
let response = await getAliasesByRoleDetailed(value.Role);
//do something with response
return response;
}, Promise.resolve());
您可以考虑使用 Promise.all: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
在你的情况下,你可以试试这个:
Promise.all(['Admin','Trainer','Manager'].map(getAliasesByRoleDetailed)).then(resultsArray => {
// do your stuff
})
Use Promise.all or Promise.allSettled Promise.all will resolve only when all of the promises have resolved hence why I think you should probably use Promise.allSettled() as it waits for all promises to complete regardless if one of them is rejected
roles=['Admin','Trainer','Manager'] var result=Promise.allSettled(roles.map(r=>getAliasesByRoleDetailed(role)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.