任何人都可以帮助我解决以下问题,我是 Javascript 中的 Async\Await 新手:
我有一个琐碎的类:
function Thing()
{
}
Thing.prototype.ShowResult = function ()
{
var result = this.GetAsync();
alert(result);
}
Thing.prototype.GetAsync = async function ()
{
var result = await this.AsyncFunc();
return result;
}
Thing.prototype.AsyncFunc = async function ()
{
return new Promise(resolve => {
setTimeout(() => {
resolve(6);
}, 2000);
});
}
Run Code Online (Sandbox Code Playgroud)
我这样称呼它:
var thing = new Thing();
thing.ShowResult();
Run Code Online (Sandbox Code Playgroud)
在看到 6 的结果之前,我预计会延迟 2 秒。
相反,我立即看到:
[对象承诺]
我怎样才能正确等待结果?谢谢你的帮助。