"await is only valid in async function" in 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";
}
}

您只能在async函数内部使用await,该错误是指您传递给新的Promise的回调(因为您在那里进入了一个新的函数范围(。

async function uploadMultipleFiles (storageFilePaths,packFilePaths,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],packFilePaths[i],packRoot) // error throws on this line
}
resolve("files uploaded")
} catch {
console.log(err)
reject("fail")
}
})
}

尝试构建新的Promise的部分实际上是多余的,因为async函数无论如何都会解析为Promise(请在此处阅读更多(。因此,您可以按照以下方式编写代码:

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 new Error("fail");
}
}

Promise回调不是异步

async function uploadMultipleFiles (storageFilePaths,packFilePaths,packRoot) {
return new Promise(async (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")
}
})
}

最新更新