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.
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.
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); }); })); };
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!