似乎你已经基本实现了你想要的。使
finally
等第二个电话,你
should
return
the inner promise
从
then
不过是回拨。
this.savePart1().then(response1 => {
if (response1.status !== 200)
return this.savePart2().then(response2 => {
// ^^^^^^
if (response1.status === 200)
⦠// display success message when both calls succeed
else
⦠// handle non-200 status from call 2
}, error => {
⦠// handle error from call 2
});
else
⦠// handle non-200 status from call 1
}), error => {
⦠// handle error from call 1
}).finally(â¦);
要对错误使用公共处理程序,您可以
switch from
.then(â¦, â¦)
to
.then(â¦).catch(â¦)
:
this.savePart1().then(response1 => {
if (response1.status !== 200)
return this.savePart2().then(response2 => {
if (response1.status === 200)
⦠// display success message when both calls succeed
else
⦠// handle non-200 status from call 2
});
else
⦠// handle non-200 status from call 1
}).catch(error => {
⦠// handle errors from both calls
}).finally(â¦);
您甚至可以通过引发异常来处理意外的状态代码:
this.savePart1().then(response1 => {
if (response1.status !== 200)
throw new Error("unexpected status "+response1.status);
return this.savePart2().then(response2 => {
if (response1.status !== 200)
throw new Error("unexpected status "+response2.status);
⦠// display success message when both calls succeed
});
}).catch(error => {
⦠// handle anything
}).finally(â¦);
如果不需要两个响应值来显示成功消息,甚至可以
unnest the
then
calls
.