In a JavaScript application, a function is returning an array filled with undefined elements when using Promise.all. This issue arises before the function completes its operations. Here's the problematic function:
<code class="js">classMethods.getQueries = function(models, dbId, dateStart, dateEnd) { return new Promise(function(resolve, reject) { // Fetch database. .then(extractQueries, reject) .then(sortQueries, reject) .then(onlyTen, reject) .then(addText, reject) .then(function(queries) { console.log("getQueries finished", queries); // Array of 10× undefined! resolve(queries); }, reject); // Functions here. }); };</code>
The addText function is identified as the root cause of the problem:
<code class="js">function addText(queries) { // This line is missing the `return` keyword. Promise.all(queries.map(function(query) { models.queries.findById(query.queryId, { raw: true, attributes: [ "query" ] }) .then(function(queryFetched) { query.text = queryFetched.query; console.log(query); // Here, missing the `return` keyword in front of `Promise.resolve(query)`. return Promise.resolve(query); }, function(error) { // Missing `return Promise.reject(error);` }); })); };</code>
To fix the issue, you must remember to return Promises in Promise.all's map callback:
<code class="js">function addText(queries) { return Promise.all(queries.map(function(query) { // Add `return` here to fix the problem. return models.queries .findById(query.queryId, { raw: true, attributes: [ "query" ] }) .then(function(queryFetched) { query.text = queryFetched.query; console.log(query); // Add `return` here. return Promise.resolve(query); }, function(error) { // Add `return` here. return Promise.reject(error); }); })); };</code>
By adding the missing return statements, you now properly wrap each database call in a Promise and return the Promise.all result when all the individual Promises have resolved. This ensures that the getQueries function receives the correct result when all queries are fetched and processed.
The above is the detailed content of Why Does Promise.all Resolve Prematurely with Undefined Elements?. For more information, please follow other related articles on the PHP Chinese website!