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
Release: 2024-10-31 08:51:30
Original
363 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template