簡體   English   中英

NodeJS - 如何在繼續執行流程之前等待多個異步調用完成?

[英]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()將結果放入一個數組中怎么辦?

  1. 我想為像['Admin','Trainer','Manager']這樣的數組中的每個元素執行getAliasesByRoleDetailed(role)並將每次執行的結果推送到resultsArray中。
  2. 所有調用都完成並且結果在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.

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