map() function with async/await

后端 未结 5 1967
后悔当初
后悔当初 2020-12-01 13:32

There is quite some topics posted about how async/await behaves in javascript map function, but still, detail explanation in bellow two examples would be nice:



        
5条回答
  •  感动是毒
    2020-12-01 13:56

    Array.prototype.map() is a function that transforms Arrays. It maps one Array to another Array. The most important part of its function signature is the callback. The callback is called on each item in the Array and what that callback returns is what is put into the new Array returned by map.

    It does not do anything special with what gets returned. It does not call .then() on the items, it does not await anything. It synchronously transforms data.

    That means that if the callback returns a Promise (which all async functions do), all the promises will be "hot" and running in parallel.

    In your example, if getResult() returns a Promise or is itself async, there isn't really a difference between your implementations. resultsPromises will be populated by Promises that may or may not be resolved yet.

    If you want to wait for everything to finish before moving on, you need to use Promise.all().

    Additionally, if you only want 1 getResults() to be running at a time, use a regular for loop and await within the loop.

提交回复
热议问题