Home  >  Article  >  Web Front-end  >  Why Does Promise.all Resolve with Undefined Values?

Why Does Promise.all Resolve with Undefined Values?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 09:10:02343browse

Why Does Promise.all Resolve with Undefined Values?

Resolving Promise.all Early: Avoiding Undefined Array

Overview

Promise.all is a powerful tool for concurrently executing multiple asynchronous operations and aggregating their results. However, if not employed correctly, it can result in unexpected behavior, such as resolving with an array of undefined values.

Problem

Consider the given code:

classMethods.getQueries = function(models, dbId, dateStart, dateEnd) {
  return new Promise(function(resolve, reject) {
    ...
    then(addText, reject)
      .then(function(queries) {
        console.log("getQueries finished", queries); // Array of 10× undefined!
        resolve(queries);
      }, reject);
  });
};

Here, the addText function returns a Promise.all of undefined values before any of the individual promises in the map callback are resolved. This causes getQueries to resolve with an array of undefined.

Solution

To resolve after all promises are fulfilled, return the promise from each map callback:

function addText(queries) {
  return Promise.all(queries.map(function(query) {
    // Return the promise to delay resolution until the operation succeeds/fails.
    return models.queries
      .findById(query.queryId, {
        raw: true,
        attributes: [ "query" ]
      })
      .then(function(queryFetched) {
        query.text = queryFetched.query;
        console.log(query);
        
        return Promise.resolve(query);
      }, function(error) {
        return Promise.reject(error);
      });
  }));
};

Avoiding Undefined in Promise.all

Remember, Promise.all accepts an array of Promise objects. Undefined values will resolve immediately, potentially causing premature resolution. Always return the promise from each individual operation to ensure a correct array of results.

The above is the detailed content of Why Does Promise.all Resolve with Undefined Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn