首页 > 解决方案 > JS | 如何使用 async await 迭代地运行函数

问题描述

我有一个功能

async function go(text)
{
    var response = await say(text);
    document.write(response + '<br>')
}

和一个承诺

function say(text)
{
    return new Promise((resolve, reject) => {
        if (enterPressed) resolve(text);
    });
}

每次用户按下回车时,我都想运行 go 函数。例如,脚本是:

go ("hello");
go ("goodbye")

我不希望这些功能立即运行,我要先打招呼,然后等待进入,然后再见。有什么方法吗?

标签: javascriptasynchronousasync-await

解决方案


怎么样:

async function foo() {
    while (true) {
        await go("hello");
        await go("goodbye");
    }
}
foo();

推荐阅读