简体   繁体   English

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

[英]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:目标是:

  1. display test then wait one second显示test然后等待一秒钟
  2. then display test then wait one second然后显示test然后等待一秒钟
  3. then display test then wait one second然后显示test然后等待一秒钟

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);

If a library like bluebird is an option then you could write:如果像bluebird这样的库是一个选项,那么您可以编写:

'use strict'
const Promise = require('bluebird')


async function test() {
  return Promise.mapSeries([1, 2, 3], async (idx) => {
    console.log('test: ' + idx);
    await Promise.delay(1000)
  });
}
test();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM