我刚刚在打字稿中快速了解Async/Await。
我正在像这样转换现有代码:
getImportanceTypes(): Promise<void> {
return this.importanceTypeService.list()
.then(items => {
this.importanceTypes = items;
});
}
自:
async getImportanceTypes(): Promise<void> {
this.importanceTypes = await this.importanceTypeService.list()
}
问题是:这真的回报了承诺吗? 它必须,因为它编译成功,但在我看来,我看到代码执行暂停在等待上,直到它完成,然后继续。
我问的原因是我对上述(不同类型的表(有大约 10 个类似的调用,我希望它们与 Promise.all 并行执行。
是的,async
函数返回承诺。(在 JavaScript 和 TypeScript 中。async
/await
"只是"用于创建和消费承诺的句法糖(但是,你知道,真正有用的糖(。
您声明返回类型的方式确实是正确的方法。然而,在这一点上存在一些分歧。:-)有些人认为,如果函数被声明为async
,您应该能够只指定其解析类型,而不是明确提及承诺。但是,目前,您确实使用Promise<x>
而不仅仅是x
。