Let's imagine that I have 10 promises running that will be passed to Promise.map()
with its default concurrency setting of 3
.
If any of the first 3 promises are rejected, will the other 7 be even started?
Bluebird's docs for map()
states the following:
Promises returned by the mapper function are awaited for and the returned promise doesn't fulfill until all mapped promises have fulfilled as well. If any promise in the array is rejected, or any promise returned by the mapper function is rejected, the returned promise is rejected as well.
It only states that if all fulfill, then the inner promises are awaited, but it's not clear to me what happens if any of them is rejected.
I'm aware that the canonical definition of the map
function is that the output's length is the same as the size of the input, but I'm not sure if Bluebird honors this.
I have achieved very similar results to @ssube's answer.
I got 10 promises, that will be resolved or rejected after a increasing timeout. The 4th one (because the array is 0-based) is rejected.
const Promise = require('bluebird')
function delay(timeout, err, i) {
return new Promise(function (resolve, reject) {
if (err) {
setTimeout(function () {
console.log('Rejected', err.message)
reject(err)
}, timeout)
} else {
setTimeout(function () {
console.log('Resolved', i)
resolve(i)
}, timeout)
}
})
}
const promises = Array.apply(null, {length: 10})
.map(Function.call, Number)
.map(function (it) {
if (it === 3) {
return delay(500 * it, new Error(it))
} else {
return delay(500 * it, null, it)
}
})
Promise.map(promises, function (p) {
console.log('Mapping', p)
return p.toString()
})
.then(function (it) {
console.log('All resolved', it)
})
.catch(function (err) {
console.log('Error', err.message)
})
This will yield:
> Resolved 0
> Mapping 0
> Resolved 1
> Mapping 1
> Resolved 2
> Mapping 2
> Rejected 3
> Error 3
> Resolved 4
> Resolved 5
> Resolved 6
> Resolved 7
> Resolved 8
> Resolved 9
So, the behaviour is the following:
Promise.map
is short-circuited whenever one of the promises being mapped is rejected. map
is never executed for any of the subsequent promises.Error 3
comes before the deliberately slower promises.