Home >Web Front-end >JS Tutorial >Why Does Promise.all() Resolve Prematurely with an Array of Undefined Values?

Why Does Promise.all() Resolve Prematurely with an Array of Undefined Values?

DDD
DDDOriginal
2024-10-31 08:51:30365browse

Why Does Promise.all() Resolve Prematurely with an Array of Undefined Values?

Resolving Promise.all() Prematurely with Array of Undefined

Problem

"Promise.all is returning an array of undefined and resolves before being done." This issue occurs when a function utilizing Promise.all() returns an array of undefined values, resolving prematurely before all promises within the array are fulfilled.

Explanation

In Promises, Promise.all() expects an array of promise objects. An array of undefined values is created here because the map callback in the addText function lacks Promise returns.

<code class="js">function addText(queries) {
  return Promise.all(queries.map(function(query) {
    // Insert a `return` statement here.
    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);
      });
  }));
};</code>

Without the return statement, the map callback will return an array of undefined values, triggering the resolution of Promise.all() prematurely, even though the queries are not yet complete.

Solution

Ensure that each map callback returns a promise by enclosing the code in return statements.

<code class="js">function addText(queries) {
  return Promise.all(queries.map(function(query) {
    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);
      });
  }));
};</code>

By doing so, Promise.all() will wait for all promises within the array to resolve before resolving itself, ensuring that the entire process completes successfully.

The above is the detailed content of Why Does Promise.all() Resolve Prematurely with an Array of 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