javascript - 异步不同步
问题描述
我有一个按钮,点击后会生成一个 http.get,然后显示一些数据,尽管我的 async/await 似乎没有正确同步。
由于我还没有完全弄清楚的原因,this.tabRows = file.contents
将在loadDateFolderFileContents()
完成之前调用。我错过了await
某个地方吗?
async ngAfterViewInit() {
if (!this.drawn) {
if(!file.contents){
await this.dataLakeService.loadDateFolderFileContents(file.parentFolder);
}
this.tabRows = file.contents;
this.redraw();
}
}
public async loadDateFolderFileContents(dateFolder: folder) {
await date.files.map(async file => {
file.contents = await this.getFileContents(dateFolder.name, file.name);
});
}
public async loadDateFolderFileContents(dateName: string, fileName: string): Promise<any> {
var url = this.buildUrl(dateName, fileName);
var fileContents = {};
await this.http.get<any>(url).toPromise()
.then(contents => {
fileContents = contents;
})
.catch(e => {
console.log(`Error retreiving file contents from url ${url}. Exception:${e}`);
});
return fileContents;
}
解决方案
map 不是异步的,所以不是:
await date.files.map(async file => {
...
尝试
await Promise.all(date.files.map(async file => {
...)
推荐阅读
- flutter - 在flutter中打开一个本地IP网页
- python - 如何在 pyqt qdock 小部件中添加图像
- nginx - nginx速率限制的理想配置
- android - 微调器选项不显示
- python - Beautifulsoup 检查 span 类和 rel
- mongodb - FailedToParse:数据库名称不能有 mongodb 的保留字符
- python - 试图抓取一个需要先用 Python 登录的网站,但没有成功
- django - Django Rest Framework - 使用电子邮件验证注册用户
- flutter - 如何访问有状态小部件中的方法?
- python-3.7 - python石榴贝叶斯网络初始化