[英]JS | How to run functions iteratively with async await
I have a function我有一个 function
async function go(text)
{
var response = await say(text);
document.write(response + '<br>')
}
And a promise还有一个 promise
function say(text)
{
return new Promise((resolve, reject) => {
if (enterPressed) resolve(text);
});
}
I want to run the go function each time when the user pressed enter.每次用户按下回车键时,我都想运行 go function 。 For example, the script is:
例如,脚本是:
go ("hello");
go ("goodbye")
I don't want these functions to be run immediately, I want first hello, then waiting for enter, then goodbye.我不希望这些功能立即运行,我要先打招呼,然后等待进入,然后再见。 Any methods?
有什么方法吗?
how about:怎么样:
async function foo() {
while (true) {
await go("hello");
await go("goodbye");
}
}
foo();
Did it.做到了。 Thanks to Sandy Berkowitz.
感谢桑迪·伯科维茨。
async function go(text)
{
var response = await say(text);
document.write(response + '<br>')
}
function say(text)
{
return new Promise((resolve, reject) => {
document.addEventListener('keydown', (e) =>
{
if (e.keyCode == 13)
{
resolve(text);
}
})
});
}
async function foo()
{
await go('go');
await go('Hello');
await go('How are you?')
}
foo();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.