Bea*_*tso 1 javascript node.js promise async-await
我被告知“await 仅在异步函数中有效”,即使它在异步函数中。这是我的代码:
async function uploadMultipleFiles (storageFilePaths,packFilePaths,packRoot) {
return new Promise((resolve,reject) => {
try {
for (i in storageFilePaths) {
await uploadFile(storageFilePaths[i],packFilePaths[i],packRoot) // error throws on this line
}
resolve("files uploaded")
} catch {
console.log(err)
reject("fail")
}
})
}
Run Code Online (Sandbox Code Playgroud)
为什么在我将其设为异步函数时会发生这种情况?是因为我使用了 for 循环吗?如果是这样,如何在没有此错误的情况下获得预期结果?
您从第 1 行开始定义的函数是async。
您在第 2 行定义并传递给 Promise 构造函数的箭头函数不是异步的。
您还使用了multiple promise anti-pattern。完全摆脱 Promise 构造函数。当您拥有它时,只需返回该值。这是async关键字的主要好处之一。
async function uploadMultipleFiles(storageFilePaths, packFilePaths, packRoot) {
try {
for (i in storageFilePaths) {
await uploadFile(storageFilePaths[i], packFilePaths[i], packRoot) // error throws on this line
}
return "files uploaded";
} catch {
console.log(err);
throw "fail";
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
164 次 |
| 最近记录: |