0%

javascript-promise-reject

JavaScript Promise Reject

See the following code, what’s the output?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function handleResponse(response) {
return new Promise((resolve, reject) => {
if (response.code !== 200) {
console.log('rejected!');
reject(response.code);
}

const {
data: { token },
} = response;
if (token) {
console.log('resolved!');
resolve(token);
}
});
}

const response = {
code: 201,
data: {
token: '123455',
},
};

handleResponse(response)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});

The output is:

1
2
3
rejected!
resolved!
201

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function handleResponse(response) {
return new Promise((resolve, reject) => {
if (response.code !== 200) {
console.log('rejected!');
return reject(response.code); // return reject here.
// return; // or return here.
}

const {
data: { token },
} = response;
if (token) {
console.log('resolved!');
resolve(token);
}
});
}

Or use the else statement to make the exclusive execution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function handleResponse(response) {
return new Promise((resolve, reject) => {
if (response.code !== 200) {
console.log('rejected!');
reject(response.code);
} else {
const {
data: { token },
} = response;
if (token) {
console.log('resolved!');
resolve(token);
}
}
});
}

Then we got the correct output as:

1
2
rejected!
201

conclusion

  • reject or returnwill not terminate the execution of the promise, it will continue to execute subsequent code.

Three ways to solve this problem:

  1. return resolved(xxx) or return reject(xxx), the return value will be ignored, so we can save a line then way 2.
  2. Add a return statement after reject(response.code).
  3. Use the if/else statement to make the exclusive execution.