[英]Call await in a callback inside an async function
Here is some code (it's an over-simplified example, I know it is dumb):这是一些代码(这是一个过于简化的示例,我知道它很愚蠢):
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function test() {
[1, 2, 3].map(() => {
console.log('test');
await sleep(1000);
});
}
test();
The objective is to:目标是:
test
then wait one secondtest
然后等待一秒钟test
then wait one secondtest
然后等待一秒钟test
then wait one secondtest
然后等待一秒钟But running this code results in a failure:但是运行此代码会导致失败:
await is a reserved word
await 是一个保留字
I know I can do fix it by using a for loop:我知道我可以通过使用 for 循环来修复它:
async function test() {
for(let i = 0; i < 3; i++) {
console.log('test');
await sleep(1000);
}
}
But is there a way to do it in a more "functional" way.但是有没有办法以更“实用”的方式做到这一点。 I mean, can I avoid the
for
loop and await inside a map?我的意思是,我可以避免
for
循环并在地图内等待吗?
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([]));
You could reduce to create a promise chain.您可以减少以创建承诺链。 However in your simplyfied case:
但是,在您的简单情况下:
(a=b=>(b==2||(console.log("test"),setTimeout(a,1000,b+1))))(0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.