Quy Quy - 1 month ago 5
Javascript Question

What is the best practice for long promise chainings within Promise.All

I'm very new to Javascript, trying to learn this language. I define a case that I've recently met from my practice.

Suppose I have several main promises, some of which return promise inside. I want to retrieve results from sort of promise functions that why I think about

Promise.all
. First off, let take a look at my example code below

var Promise = require('bluebird');
promise = []
function promise1(){
return new Promise(function(resolve, reject){
console.log('promise1');
resolve('promise1');
});
}
function promise2(){
return new Promise(function(resolve, reject) {
console.log('promise2');
resolve('promise2');
});
}
function promise3(){
promise2().then(function(){
return new Promise(function(resolve, reject) {
console.log('promise3');
resolve('promise3')
})
})
}


Upper piece of code, 2 main promises are
promise1
and
promise3
.
promise2
will be returned by
promise3
. I'm demonstating
promise3
as a long promise chaning. To run, I initialized

promise = [promise1(), promise3()];
Promise.all(promise).then(function(data){
console.log('done', data);
})


Outcome was


promise1

promise2

promise3

done [ 'promise1', undefined ]


but I am expecting that


done [ 'promise1', 'promise3' ]


My question is what is the best practice in this case?

Answer

promise3 is missing a return. With this it works as expected.

function promise3(){
  return promise2().then(function(){
  // ^^^ missing return here
    return new Promise(function(resolve, reject) {
      console.log('promise3');
      resolve('promise3')
    })
  })
}
Comments