Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve Promise.all containing array of promises with timeout

In the below example I'd like to resolve each element of the array after a couple of seconds. How it behaves now is it will solve the Promise after 4 seconds, I expect it to resolve after 16seconds because there is 4 element.

const numbers = [1, 2, 3, 4];

const promises = numbers.map(number => {
    return new Promise(resolve => {
        setTimeout(() => {
          console.log(number);
            resolve(number);
        }, 4000);
    });
});


Promise.all(promises).then( () => {
    console.log("Done");
});
like image 330
Pedram marandi Avatar asked Dec 19 '22 03:12

Pedram marandi


2 Answers

Using the new Async / Await, that's now pretty much widely implemented. And if not, you can transpile for old browsers.

You can create code, that's much more linear and easier to follow.

It's also worth mentioning, bluebird has a promise based map, that has a concurrency option that would be ideal for the map bit.

const numbers = [1, 2, 3, 4];

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

//pretend show number async
async function showNumber(l) {
  return new Promise((resolve) => {
    setTimeout(() => { console.log(numbers[l]); resolve(); });
  });
}

async function doNumbers() {
  for (let l = 0; l < numbers.length; l ++) {
    await delay(4000);
    await showNumber(l);    
  }
  console.log("Done");
}

doNumbers();
like image 50
Keith Avatar answered Dec 24 '22 00:12

Keith


Increment your timer everytime, by multiplying it by number :

const numbers = [1, 2, 3, 4];
    
    const promises = numbers.map(number => {
        return new Promise(resolve => {
            setTimeout(() => {
              console.log(number);
                resolve(number);
            }, number*4000);
        });
    });
    
    
    Promise.all(promises).then( () => {
        console.log("Done");
    });

It displays "Done" after 16 seconds.

like image 28
Guillaume Georges Avatar answered Dec 24 '22 02:12

Guillaume Georges