TypeScript中await Promise后如何直接获取已解析值?
如何在await Promise后获取其解析值(除.then外)?
先看你的代码场景:
定义返回Promise的函数:
HelloWorld():Promise<string> { return new Promise(resolve => { setTimeout(() => { alert("IN"); resolve('Hello World!'); }, 2000); }); }
执行逻辑:
async onClick() { var p:Promise<string> = this.HelloWorld(); await(p); alert(p); // 弹出[object Promise]而非预期的'Hello World!' }
为什么会弹出[object Promise]?
await p只是等待这个Promise完成状态变更,但变量p本身始终是Promise实例,不会因为await就变成它的解析值。所以直接alert(p)只会输出Promise对象的字符串表示。
除了.then之外的获取方式
最直接且符合async/await设计初衷的方式,是将await的结果赋值给变量:
async onClick() { var p:Promise<string> = this.HelloWorld(); const resolvedValue = await p; // 这里拿到的就是Promise解析后的'Hello World!' alert(resolvedValue); }
如果出于实验目的,还可以用Promise.all包裹Promise实例,通过解构获取结果(虽非必要,但确实是.then之外的方式):
async onClick() { var p:Promise<string> = this.HelloWorld(); const [resolvedValue] = await Promise.all([p]); alert(resolvedValue); }
补充说明
Promise的设计本身就不支持直接从实例上读取解析后的值(除非自行封装额外存储逻辑),规范的方式就是通过await(async/await语法)或者.then()获取结果。其中await是.then()的语法糖,也是当前异步代码的主流写法,比.then更简洁易读。
内容的提问来源于stack exchange,提问作者gnitsuk
相关产品推荐
相关产品推荐

