Waiting for a call in a callback inside an asynchronous function

Here's some code (this is a simplified example, I know it's 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 goal is as follows:

  • display test

    then wait one second
  • then display test

    then wait one second
  • then display test

    then wait one second

But running this code results in an error:

Waiting is a reserved word

I know I can fix this using a for loop:

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 escape the loop for

and wait inside the card?

+3


source to share


2 answers


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

      

http://jsbin.com/jocopixaro/edit?console



You can shrink to create a promise chain. However, in your simple case:

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

      

+2


source


If a library like bluebird you can write:



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

      

+1


source







All Articles