在JavaScript 應用程式中,函數在以下情況下傳回充滿未定義元素的陣列:使用Promise.all。此問題在函數完成其操作之前出現。這是有問題的函數:
<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>
addText 函數被確定為問題的根本原因:
<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>
要解決此問題,您必須記得在Promise.all 的映射回調中返回Promise:
<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>
透過添加缺少的return 語句,您現在可以正確地將每個資料庫呼叫包裝在Promise 中,並在所有單獨的Promise 都滿足時返回Promise.all 結果解決了。這確保了 getQueries 函數在取得和處理所有查詢時收到正確的結果。
以上是為什麼 Promise.all 會因為未定義的元素而過早解析?的詳細內容。更多資訊請關注PHP中文網其他相關文章!