简体   繁体   English

NodeJS - 如何在继续执行流程之前等待多个异步调用完成?

[英]NodeJS - How to wait for multiple Async calls to finish before continuing execution flow?

I have a function getAliasesByRoleDetailed(role) that takes care of fetching user data given a role (this function uses axios to fetch data).我有一个 function getAliasesByRoleDetailed(role)负责获取给定role的用户数据(此 function 使用 Z38C3787939C7B0B6C17D73FCE3D28 来获取数据)。

The output of this function is something like this:这个 function 的 output 是这样的:

[     
    {
        alias: 'xxxx',
        Role: 'Admin',
        grantedBy: 'rnfnf',
        timestamp: '1591375676333'
    },
    {
        alias: 'vbjp',
        Role: 'Admin',
        'Granted By': 'hjkds',
        timestamp: '1588013678236'
    }
]

It is possible to do something like this:可以这样做:

const response = await getAliasesByRoleDetailed(role);

and then keep doing stuff with response once the data is available.然后在数据可用后继续进行response

But what if I want to make multiple calls to this getAliasesByRoleDetailed(role) function and .push() the results into an array before moving on with the code execution?但是,如果我想在继续执行代码之前多次调用这个getAliasesByRoleDetailed(role) function 和.push()将结果放入一个数组中怎么办?

  1. I want to execute the getAliasesByRoleDetailed(role) for each element in an array like ['Admin','Trainer','Manager'] and push the results of each execution into a resultsArray .我想为像['Admin','Trainer','Manager']这样的数组中的每个元素执行getAliasesByRoleDetailed(role)并将每次执行的结果推送到resultsArray中。
  2. After all calls have finished and the results are available in the resultsArray , I'd like to continue with my logic, using the resultsArray data.所有调用都完成并且结果在resultsArray中可用之后,我想继续我的逻辑,使用resultsArray数据。

So, ideally:所以,理想情况下:

//Inside a function...

[getting data using getAliasesByRoleDetailed(role) ...]

resultsArray.forEach( (e) => {
    //Do something useful with all these element I now have!
}

I've tried a couple of solutions with async/await and .forEach() but keep getting stuck.我用 async/await 和.forEach()尝试了几个解决方案,但一直卡住。 Is there a simple solution for this?有一个简单的解决方案吗?

If I understand your question correctly, you'd probably want to make use of Promise.all .如果我正确理解您的问题,您可能想使用Promise.all

This will wait for all the inner promises (promises passed into the function) to resolve before resolving itself.这将等待所有内部承诺(传递给函数的承诺)在自行解决之前解决。

// 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

You can then flatten the array using Array.flat然后,您可以使用Array.flat展平阵列

// inside the same function
const flattenResults = Array.flat(results);

Since you mentioned async/await, I assume that getAliasesByRoleDetailed returns a Promise .既然你提到了异步/等待,我假设getAliasesByRoleDetailed返回一个Promise Therefore, you have to do something like因此,你必须做类似的事情

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());

You could consider to use Promise.all: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all您可以考虑使用 Promise.all: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

In your situation, you can try this:在你的情况下,你可以试试这个:

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 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.

相关问题 Node.js-等待多个异步调用完成,然后继续执行代码 - Node.js - Wait for multiple async calls to finish before continuing in code 如何在继续测试之前等待 Vue 组件的异步安装完成 - How to wait for async mounted of Vue component to finish before continuing with testing 如何在继续async.series之前等待findOneAndUpdate完成 - How to wait for findOneAndUpdate to finish before continuing async.series NodeJS Plotly - 如何在继续之前等待 getImage 完成 - NodeJS Plotly - how to wait for getImage to finish before continuing 如何继续等待一个功能完成? - How to wait for one function to finish before continuing? 如何让nodejs在继续之前等待mongodb连接(以阻塞方式调用异步) - How to make nodejs wait for mongodb connection before continuing (calling async in blocking way) 如何在继续执行脚本之前有效地等待链接文件完成运行 - How to efficiently wait for a linked file to finish running before continuing with script 如何让程序在继续使用javascript之前等待if语句完成? - How to make the program wait for the if statement to finish before continuing in javascript? 如何在继续下一行代码之前等待 .map() 完成执行 - How to wait for .map() to finish executing before continuing on to next lines of code 如何在继续之前等待递归 function 完全完成? - How can I wait for a recursive function to completely finish before continuing?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM