有人告诉我,“等待仅在异步函数中有效”,即使它在异步函数中也是如此。这是我的代码:
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循环吗?如果是这样,如何在没有此错误的情况下获得预期结果?
答案 0 :(得分:5)
您从第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";
}
}
答案 1 :(得分:2)
您只能在 await
函数内使用 async
,该错误是指您传递给新的 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
(更多信息{{ 3}})。因此,您可以按照以下方式编写代码:
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");
}
}
答案 2 :(得分:-2)
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")
}
})
}