JavaScript async map 回傳 Promise 陣列?檢查 await 與 return
本文目錄
把 map() 的 callback 改成 async 後,原本的資料陣列會變成 Promise[]。TypeScript 可能在你把它指定給 number[] 時報 TS2322。先用 await Promise.all(items.map(...)) 取得每筆結果;如果拿到的是一排 undefined,再檢查 callback 有沒有把值傳回來。
外層 await 有沒有在等每個元素?
map() 把 callback 的回傳值放進新陣列,async callback 的回傳值則是 Promise。一般陣列本身可以直接當成值,所以 await pending 會得到原陣列。存為 check-map.mjs,用 node check-map.mjs 執行:
import assert from 'node:assert/strict';
const ids = [2, 4, 6];const loadScore = async (id) => id * 10;
const pending = ids.map(async (id) => loadScore(id));assert.equal(await pending, pending);assert.equal(pending.every((item) => item instanceof Promise), true);assert.deepEqual(await Promise.all(pending), [20, 40, 60]);
const missing = await Promise.all(ids.map(async (id) => { await loadScore(id);}));assert.deepEqual(missing, [undefined, undefined, undefined]);
const scores = await Promise.all(ids.map(async (id) => { const score = await loadScore(id); return score;}));assert.deepEqual(scores, [20, 40, 60]);上面第二組的每個 Promise 都完成了,但 callback 執行到區塊末尾時沒有回傳值。如果連 await loadScore(id) 都省掉,而且也沒有 return,外層甚至可能先完成,內層失敗也不會沿原先的 Promise 傳回來。用簡寫 id => loadScore(id) 可直接傳回已有的 Promise。 ECMAScript:Array.prototype.map ECMAScript:Promise.all
分批時在每批開始前才呼叫 map
對整份清單先做 items.map(loadScore),之後才把 Promise 陣列切片,工作可能已經全部啟動。若一批最多允許兩筆,把建立 Promise 的動作放進迴圈。可把下例接在上一段後執行。
let active = 0;let peak = 0;const started = [];const rows = [];
async function countWhileLoading(id) { started.push(id); active += 1; peak = Math.max(peak, active); try { return await loadScore(id); } finally { active -= 1; }}
for (let offset = 0; offset < ids.length; offset += 2) { const batch = ids.slice(offset, offset + 2); const results = await Promise.all(batch.map(countWhileLoading)); rows.push(...results);}
assert.deepEqual(started, [2, 4, 6]);assert.deepEqual(rows, [20, 40, 60]);assert.equal(peak, 2);每批要等最慢的一筆才開始下一批。一筆 reject 時,這段迴圈會停止啟動下一批,已啟動的同批工作可能還在執行。若畫面要保留各筆的成功與失敗結果,改用 Promise.allSettled 的部分失敗處理 並明確決定是否繼續下一批。若問題出在外層用了不回傳結果陣列的 forEach(),可看 forEach 的非同步控制流程。
參考資料: