user700077 user700077 - 4 months ago 8
Node.js Question

Making a Promise resolve only when all 'then's in the chain have been resolved

I'm under the impression that a chain of Promises returns the last Promise in the chain of 'then's. However, that doesn't seem to be the case when I tested the following:

function a() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log('1');
resolve(1);
}, 1000);
}).then((num) => {
setTimeout(function() {
console.log('2');
return 2;
}, 1000);
});
}

a().then((num) => {
console.log('a is done running');
console.log('finally, ', num);
});


The code currently outputs

1
a is done running
finally, undefined
2


Shouldn't the bottommost fulfilment function run only when all Promises in the chain have completed?

How would I get it to output the following?

1
2
a is done running
finally, 2

Answer

You can do that by actually returning a new promise:

function a() {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            console.log('1');
            resolve(1);
        }, 1000);
    }).then((num) => {
        return new Promise((resolve) => {
          setTimeout(function() {
              console.log('2');
              return resolve(2);
          }, 1000);
        })
    });
}

// the "then" here actually comes from the second promise.
a().then((num) => {
    console.log('a is done running');
    console.log('finally, ', num);
});
Comments