reject状态传递
reject状态传递途中会跳过成功处理函数
new Promise((resolve, reject) => {
reject();
})
.then(() => { console.log('1.ok') }) //跳过
.then(() => { console.log('2.ok') }, () => { console.log('2.fail') }) //如果不返回新的Promise,默认会回到成功状态
.then(() => { console.log('3.ok') }, () => { console.log('3.fail') });
输出:
2.fail
3.ok
在then中返回的新Promise中reject也一样
new Promise((resolve, reject) => {
resolve();
})
.then(() => { console.log('1.ok') })
.then(() => {
return new Promise((resolve, reject) => {
reject();
});
})
.then(() => { console.log('2.ok') }) //跳过
.then(() => { console.log('3.ok') }, () => { console.log('3.fail') });
输出:
1.ok
3.fail
通过将成功处理函数置为null插入可选的流程
new Promise((resolve, reject) => {
//登录后检查登录状态,若已登录则resolve,否则reject
console.log('running');
console.log('already logged in');
resolve();
})
.then(null, msg => {
//登录
console.log('msg: ' + msg);
console.log('login');
})
.then(() => {
//继续
console.log('go on');
});
输出:
running
already logged in
go on
通过reject执行可选的流程
new Promise((resolve, reject) => {
//登录后检查登录状态,若已登录则resolve,否则reject
console.log('running');
reject('not logged in');
})
.then(null, msg => {
//登录
console.log('msg: ' + msg);
console.log('login');
})
.then(() => {
//继续
console.log('go on');
});
输出:
running
msg: not logged in
login
go on
抛出和处理错误
抛出错误会触发失败处理函数,后面的catch捕获不到
new Promise((resolve, reject) => {
throw new Error('failed');
})
.then(() => { console.log('ok') }, () => { console.log('fail') /*执行这里*/ })
.catch(err => {
console.log(err); //捕获不到
});
输出:
fail
使用catch捕获
new Promise((resolve, reject) => {
throw new Error('failed');
})
.then(() => { console.log('ok') }) //没有失败处理函数
.catch(err => {
console.log('error catched: ' + err.message); //执行这里
});
输出:
error catched: failed
不能在回调函数里抛出错误,捕获不到
new Promise(resolve => {
console.log('running');
setTimeout(() => {
console.log('will throw error');
throw new Error('failed');
}, 1000);
})
.catch(err => {
console.log('error catched'); //捕获不到
});
输出:
running
will throw error
/Users/Tom/Desktop/Projects/_tests/PromiseTest/main.js:40
throw new Error('failed');
^
Error: failed
at Timeout.setTimeout (/Users/Tom/Desktop/Projects/_tests/PromiseTest/main.js:40:19)
at ontimeout (timers.js:380:14)
at tryOnTimeout (timers.js:244:5)
at Timer.listOnTimeout (timers.js:214:5)