有人告诉我“等待仅在异步函数中有效”,即使它在异步函数中也是如此。这是我的代码:
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")
}
})
}
当我使它成为异步函数时,为什么会发生这种情况?是因为我正在使用for循环吗?如果是这样,如何在没有此错误的情况下获得预期结果?
从第1行开始定义的函数是async
。
您在第2行上定义并传递给Promise构造函数的箭头函数不是异步的。
您还使用了多重承诺反模式。完全摆脱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";
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句