gpt4 book ai didi

javascript - 在异步函数内的回调中调用 await

转载 作者:数据小太阳 更新时间:2023-10-29 05:21:26 24 4
gpt4 key购买 nike

这是一些代码(这是一个过于简化的示例,我知道它很愚蠢):

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

async function test() {
[1, 2, 3].map(() => {
console.log('test');
await sleep(1000);
});
}
test();

目标是:

  1. 显示测试然后等待一秒钟
  2. 然后显示测试然后等待一秒
  3. 然后显示测试然后等待一秒

但是运行这段代码会导致失败:

await is a reserved word

我知道我可以使用 for 循环修复它:

async function test() {
for(let i = 0; i < 3; i++) {
console.log('test');
await sleep(1000);
}
}

但是有没有办法以更“实用”的方式做到这一点。我的意思是,我可以避免 for 循环并在 map 中等待吗?

最佳答案

const result = await [1, 2, 3].reduce(async function(prom, v){   
const result= await prom;
await sleep(1000);
result.push(v);
return result;
}, Promise.resolve([]));

您可以减少以创建 promise 链。但是,在您的简单情况下:

(a=b=>(b==2||(console.log("test"),setTimeout(a,1000,b+1))))(0);

关于javascript - 在异步函数内的回调中调用 await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44568597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com