How to use the Promise function inside a JavaScript array map?

Estimated read time 2 min read

In JavaScript, you can use the Promise function inside an Array.map() method to execute asynchronous operations on an array of items in parallel. Here’s an example:

const items = ['item1', 'item2', 'item3'];

const promises = items.map(item => {
  return new Promise(resolve => {
    // Do some asynchronous operation here
    const result = item.toUpperCase();
    resolve(result);
  });
});

Promise.all(promises)
  .then(results => console.log(results))
  .catch(error => console.log(error));

In this example, the items array contains three items. The map() method is used to iterate over each item in the array and create a new array of Promise objects, one for each item. Inside the map() function, a new Promise is created that performs some asynchronous operation, in this case, simply converting the item to uppercase. The resulting Promise object is returned from the function and added to the promises array.

Once all the promises are created, the Promise.all() method is used to wait for all the promises to resolve. When all the promises are resolved, the resulting data is returned as an array of resolved values, which are then logged to the console.

Note that if any of the promises fail, the Promise.all() method will catch the error and reject the overall promise.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply