1 回答

TA貢獻1877條經驗 獲得超1個贊
盡量弄清楚你是想要一個承諾,還是要解決的結果
在您的第一個代碼塊中,您正確地打算組裝一個承諾列表,以便您可以將它們與 a 合并Promise.all,然后等待整個結果,與await.
但是,在我看來,您不小心await在內部函數(在.map)內分別對每個 promise 進行了處理,因此輸入的數組Promise.all不再是一個 promise 數組。
而不是這個:
await Promise.all(files.map(
async (file) => {
let url= await uploadFileAndSave(req, file);
await saveFileDB(file,url);
// This inner function "async (file) => ..." does not
// have a `return` statement, so it returns `undefined`, rather than
// the promise you intended to return. This is because you `await`ed
// the promise already, rather than `return`ing it to the outer loop.
}
))
我建議這樣做:
await Promise.all(files.map(
async (file) => {
let url= await uploadFileAndSave(req, file);
return saveFileDB(file,url);
// Now the inner "async (file) =>" function returns
// a promise (because that is the result type of saveFileDB)
}
))
作為文體問題,您可能還想將“let url =”更改為“const url =”。每當您知道您正在創建一個變量,其值在被銷毀之前不會改變時,將其標記為const. 這在調試時(例如,在代碼變長之后)對讀者和您自己都有幫助,而且當您嘗試重新分配它時,Javascript 甚至您的代碼編輯器都會警告您。
添加回答
舉報