I'm struggling to figure out how to properly bubble errors with promises.
Specifically, what I'm talking about is a situation where there is nested promises. I want to be able to implictly pass the resolve
and reject
functions to the nested promise.
It'll be more obvious what I mean by showing some code.
The following is what I have been using successfully:
var asyncIsEven = function(number) {
return new Promise(function(resolve, reject){
if (number % 2 == 0) { return resolve(number) }
else { return reject("number is odd") }
})
}
var A = function (number) {
return new Promise(function(resolve, reject){
return asyncIsEven(number).then(resolve).catch(reject)
})
}
Here, it seems pretty unnecessary to write then(resolve).catch(reject)
.
I understand that I can just make function A
return asyncIsEven(number)
, but there are situations when I want to provide a then
function but have no need to provide a catch
function (or vice versa).
What I've tried:
this works, but is not really what I want because I'm not providing a then
handler to the nested callback
var A = function (number) {
return Promise.all([asyncIsEven(number)])
}
// or alternatively
var A = function(number) {
return asyncIsEven(number)
}
This is what I want to write, but it doesn't work
var A = function(number) {
return new Promise(function(resolve, reject) {
return asyncIsEven(number).then(resolve)
})
}
When I say it "doesnt work", what I mean is that I cannot write the following:
A(2).then(function(number) {
console.log(`${number} is even`)
}).catch(function(err) {
console.log(err)
})
Because the catch
function will never be called.
In other words - if I define function A
to return asyncIsEven(number).then(resolve)
, how can I bubble errors from asyncIsEven
up to the reject
callback given to A
?