我在这里读过很多关于使用等待/异步的问题,但现在我有了不同的情况。我想在一个for循环中使用等待,这个循环存在于一个函数中,函数中包含等待关键字,但不知怎么它不起作用,使用了两次等待:
async import(){
await this.sp.getResults(queryParams)
.then(data => {
for(let i=0; i < data["results"].length; i++){
this.setData(data["results"][i], this.data_to_import[i]); // how can I use await here
}
})
.catch(
error => console.log(error);
)
}
我得到以下错误:
的“等待”表达式仅允许在异步函数中和模块的最高>级别上。
如果有我的具体问题的答案,我很抱歉,如果你能分享链接,以便我可以查找它,我将不胜感激。谢谢你的帮助!
发布于 2020-06-30 00:14:10
因为您的内部函数(data => ...
)没有异步关键字:
async import(){
await this.sp.getResults(queryParams)
.then(async data => {
for(let i=0; i < data["results"].length; i++){
await this.setData(data["results"][i], this.data_to_import[i]);
}
})
.catch(
error => console.log(error);
)
}
要么添加它,要么使用getResults
等待的结果
async import(){
try {
const data = await this.sp.getResults(queryParams);
for(let i=0; i < data.results.length; i++) {
await this.setData(data.results[i], this.data_to_import[i]);
}
} catch(e) {
console.error(e);
}
}
https://stackoverflow.com/questions/62652958
复制相似问题