JavaScript Promise Reject
See the following code, what’s the output?
1 | function handleResponse(response) { |
The output is:
1 | rejected! |
Why?
reject
or resolve
will not terminate the execution of the promise, it will continue to execute subsequent code.
To solve this problem, you can add a return
statement after reject(response.code)
.
1 | function handleResponse(response) { |
Or use the else statement to make the exclusive execution.
1 | function handleResponse(response) { |
Then we got the correct output as:
1 | rejected! |
conclusion
reject
orreturn
will not terminate the execution of the promise, it will continue to execute subsequent code.
Three ways to solve this problem:
return resolved(xxx)
orreturn reject(xxx)
, the return value will be ignored, so we can save a line then way 2.- Add a
return
statement afterreject(response.code)
. - Use the
if/else
statement to make the exclusive execution.