Promise.all Returning Undefined Array and Resolving Prematurely
Promise.all is designed to accept an array of Promise objects and resolve once all of the Promises in the array have resolved. In the provided code, however, the issue arises because the callback function passed to Promise.all's map doesn't return a Promise.
Within the addText function:
<code class="javascript">function addText(queries) { return Promise.all(queries.map(function(query) { // Missing `return` statement causes undefined values in the array models.queries .findById(query.queryId, { raw: true, attributes: [ "query" ] }) .then(function(queryFetched) { query.text = queryFetched.query; console.log(query); // Return the updated query as a resolved Promise return Promise.resolve(query); }, function(error) { // Return the error as a rejected Promise return Promise.reject(error); }); })); };</code>
Here's what's happening:
To fix this issue and ensure that Promise.all resolves only after all Promises in the callback have resolved, the callback must explicitly return Promises:
<code class="javascript">function addText(queries) { return Promise.all(queries.map(function(query) { // Added `return` statement to wrap the Promise in the callback 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>
Now, the map callback returns Promises, which Promise.all can properly handle and resolve only once all Promises have resolved.
The above is the detailed content of Why is Promise.all Returning an Undefined Array and Resolving Prematurely?. For more information, please follow other related articles on the PHP Chinese website!