mercredi 26 septembre 2018

The first then for my promise returns a promise even though the rejected method has no return function in it

In the code below, the first .then() chained to the addTwo function calls the reject method because I'm checking if type of a and b are "errors", which is impossible.

I expected the output to stop at "we have an error boss" without continuing since the reject method, unlike the resolve method, does not have a "return addTwo" statement.

But the output reveals that the code continues on to the next then call, and the output is "answer of second addition : undefined". How come the code doesn't just stop at the first then call, since the reject method doesn't return a Promise?

var addTwo = (a, b) => {
    return new Promise((resolve, reject) => {   
        if(typeof a === 'number' && typeof b === 'number'){
            resolve(a + b)
        }else{
            reject("a or b or both were not numbers")
        }
    })
}


addTwo(5, 6).then((res) => {
    console.log("Answer of addition: " + res)
    return addTwo(res, 100)
}, (err) => {
    console.log("We have an error boss: " + err)
}).then((res) => {
    console.log("Answer of second addition: " + res)
}, (err) => {
    console.log("We have an error boss: " + err)
})




Aucun commentaire:

Enregistrer un commentaire