ThomasThiebaud ThomasThiebaud - 2 months ago 7
Node.js Question

Is Promise.all([]) equivalent to promise.then().then()

Is this code

Promise.all([
promise1,
promise2,
])
.then(() => doSomething())


equivalent to

promise1
.then(() => promise2)
.then(() => doSomething())


I thought they were equivalent, but they do not behave the same on an fortunejs and mocha application. Below are more details about this application




I'm using fortune.js and I would like to write some tests using mocha. What I'm trying to achieve is to use the
beforeEach
hook to truncate tables in the database and then insert some predifined values. So if I have two tables called
customer
and
user
I will do something like this

beforeEach(function () {
return Promise.all([store.delete('user'), store.delete('customer')])
.then(() => store.create('customer', {
id: '0987654321234567890',
// More data
}))
.then(() => store.create('user', {
id: 'qwertyuioppoiuytrewq',
customer: '0987654321234567890',
// More data
}));
});


This code is not stable and works sometimes and sometimes not without I can find why (around 50% success rate)

But if I switch to this code it is working :

beforeEach(function () {
return store.delete('customer')
.then(() => store.delete('user'))
.then(() => store.create('customer', {
id: '0987654321234567890',
// More data
}))
.then(() => store.create('user', {
id: 'qwertyuioppoiuytrewq',
customer: '0987654321234567890',
// More data
}));
});


I thought that

Promise.all([
promise1,
promise2,
])
.then(() => doSomething())


was equivalent to

promise1
.then(() => promise2)
.then(() => doSomething())


Since store.delete returns a Promise, why do I have a different behavior ?

Answer

This

Promise.all([
  promise1,
  promise2,
])
.then(() => doSomething())

starts to execute both promises at the same time and calls then() when the latest finished, while this

promise1
    .then(() => promise2)
    .then(() => doSomething())

starts with the first promise and when that's finished executes the second, and so forth.