Search code examples
promisebluebird

javascript - bluebird is not starting promises correctly


I am having a problem with bluebird concurreny. Basically I want my promises to be fired one after an other. I found that this can be done using bluebird. This is my code:

var  getdep = Promise.promisify(
  function getdep(module, cb ) {
    console.log(module + " ...start ...")
    ls(module, function(data) {
      cb(null, data);
    });
  });

 Promise.all([0,1,2,3,].map(function(data){
   return getdep("uglify-js@2.4.24");
 }, {concurrency: 1}))
 .then(function(all){
   console.log(all);
 })
 .catch(function(err){
   console.log(err);
 });

What I respected is something like ({concurrency: 1}).

uglify-js@2.4.24 ...start ...
loading: uglify-js@2.4.24@latest
loading: uglify-js@2.4.24@latest
loading: uglify-js@2.4.24@latest
loading: uglify-js@2.4.24@latest
....
uglify-js@2.4.24 ...start ...
loading: uglify-js@2.4.24@latest
loading: uglify-js@2.4.24@latest
loading: uglify-js@2.4.24@latest
loading: uglify-js@2.4.24@latest

... and so on

but what I am having is:

uglify-js@2.4.24 ...start ...
uglify-js@2.4.24 ...start ...
uglify-js@2.4.24 ...start ...
uglify-js@2.4.24 ...start ...
loading: uglify-js@2.4.24@latest

That means bluebird is starting all my promises at the same time. Can you please tell me what is wrong in my code ? thanks


Solution

  • You are using Array#map not Promise.map

     Promise.all(
        [0,1,2,3,].map(function(data){
     //      array.map
             return getdep("uglify-js@2.4.24");
         }, {concurrency: 1}) // end of array.map 
     )
     .then(function(all){
       console.log(all);
     })
     .catch(function(err){
       console.log(err);
     });
    

    Array.map doesn't understand the {concurrency:1} argument - it uses that as the thisArg for the callback

    To use Promise.map, use Promise.map like this

     Promise.map([0,1,2,3,], function(data){
         return getdep("uglify-js@2.4.24");
     }, {concurrency: 1}))
     .then(function(all){
       console.log(all);
     })
     .catch(function(err){
       console.log(err);
     });