Search code examples
javascriptasynchronouspromisebluebirdasync.js

use promise series instead async series


I use the following async.js code

var arr = ['1', '2'];
async.mapSeries(arr, getInfo, (e, res) => {
  console.log(res);
});

function getInfo(name, callback) {
  setTimeout(() => {
    callback(null, name + ' from async');
  }, 500);
}

Now I want to convert it to bluebird promise and I try the following but the delay is not working, I think that probably I need to and the Promise.delay but not sure how to use it...

Promise.mapSeries(arr, function(getInfo) {
  return getInfo + ' from promise'
}).then(function(results) {
  console.log(results)
});

Solution

  • You seem to be looking for

    function getInfo(name) {
      return Promise.delay(500, name + ' from async');
    }
    Promise.mapSeries(arr, getInfo).then(results => {
      console.log(results)
    });
    

    Alternatively you could have written Promise.delay(500).then(() => name + ' from async').