I am studying javascript promises. The first code works fine, but the second code gives an error.
When catching errors, isn’t it sufficient for the reject function to be called? I don’t understand the difference between using and not using the return statement in this context.
I expect not only first code but also second code work fine
const f1 = () => {
return new Promise((res, rej) => {
setTimeout(() => {
res("number1:complete")
}, 2000)
})
}
const f2 = (message) => {
console.log(message)
return new Promise((res, rej) => {
setTimeout(() => {
rej("number2:fail")
}, 3000)
})
}
//first code >> success
f1()
.then(a => {
return f2(a)
})
.catch(console.log)
//second code >> error
f1()
.then(a => {
f2(a)
})
.catch(console.log)
3
Answers
In the second code snippet, you are missing a return statement
reject
does make the related promise rejected, but that’s it.In your second example since you’re not returning the promise it won’t affect the resulting promise.
Your resulting promise from your
.then
is immediately resolved as it implicitly returnsundefined
..catch
only applies to the promise object, which was resolved. It doesn’t control anything about another promise that has been "detached" somewhere along the way.Without the
return
statement in this case, thePromise
is never observed. By returning aPromise
here:that allows the chain of promise handlers (any additional calls to
.then()
, any call to.catch()
) to observe the result of thatPromise
. Without returning it, the call tof2()
just goes unobserved because there is no.then()
or.catch()
attached to it.A very common real-world example is calling
.json()
on the result of afetch()
:By returning the
Promise
fromresult.json()
you can use thatPromise
in a follow-up.then()
call in the overall chain. Without returning it, there’s nothing to follow-up on.