如何调用异步 JavaScript 函数?

use*_*290 5 javascript async-await

任何人都可以帮助我解决以下问题,我是 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 秒。

相反,我立即看到:

[对象承诺]

我怎样才能正确等待结果?谢谢你的帮助。

小智 0

虽然 AsyncFunc 和 GetAsync 是异步函数。ShowResult 函数不是。父函数也必须是异步的。下面的代码返回 6。

function Thing()
{
}

Thing.prototype.ShowResult = async function ()
{
    var result = await 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);
    });
}

var thing = new Thing();

thing.ShowResult(); 
Run Code Online (Sandbox Code Playgroud)