如何解决for循环中的“ 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")
}
})
}
为什么我将其设为异步功能时会发生这种情况?是因为我正在使用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";
}
}
,
您只能在 await
函数内使用 async
,该错误是指您传递给新的 Promise
(因为您要在此处输入新的功能范围)。
async function uploadMultipleFiles (storageFilePaths,packRoot) {
return new Promise((resolve,reject) => { // <========= this arrow function is not async
try { // so you cant use await inside
for (i in storageFilePaths) {
await uploadFile(storageFilePaths[i],packRoot) // error throws on this line
}
resolve("files uploaded")
} catch {
console.log(err)
reject("fail")
}
})
}
您尝试构造新的 Promise
的部分实际上是多余的,因为async
函数将始终解析为Promise
(更多信息{{ 3}})。因此,您可以按照以下方式编写代码:
async function uploadMultipleFiles (storageFilePaths,packRoot) {
try {
for (i in storageFilePaths) {
await uploadFile(storageFilePaths[i],packRoot) // error throws on this line
}
return "files uploaded"
} catch {
console.log(err)
throw new Error("fail");
}
}
,
Promise
回调不同步
async function uploadMultipleFiles (storageFilePaths,packRoot) {
return new Promise(async (resolve,reject) => {
try {
for (i in storageFilePaths) {
await uploadFile(storageFilePaths[i],packRoot) // error throws on this line
}
resolve("files uploaded")
} catch {
console.log(err)
reject("fail")
}
})
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。