【发布时间】:2021-04-29 18:05:24
【问题描述】:
我有一个按钮,点击后会生成一个 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;
}
【问题讨论】:
-
这个:
return fileContents;--> 这能回答你的问题吗? How do I return the response from an asynchronous call? -
这很奇怪,你正在等待,但你有一个
.then不会被等待。只需让 content = await this.http.get .... 并将其放入 try catch -
@KeithNicholas 感谢您的提示。我对 JS/TS + Promises 的整个世界还是陌生的,所以我仍然在这里和那里挣扎。
标签: javascript angular typescript asynchronous