promise的异常传透
举个栗子:
/**
* promise异常传透???
* (1)、当使用promise的then链式调用时,可以在最后指定失败的回调。
* (2)、前面任何操作出了异常,都会传到最后失败的回调中处理。
*/
//promise1
new Promise((resolve,reject) => {
//假如异步处理成功,返回成功的数据
resolve('resolve1');
})
.then(
value => {
console.log('promise2-->接收到promise1的数据为: ' + value);
//默认: return undefined
}
)
.then(
value => {
console.log('promise3-->接收到promise2的数据为:' + value);
}
)
运行结果:
promise2–>接收到promise1的数据为: resolve1
promise3–>接收到promise2的数据为:undefined
举个栗子
//promise1
new Promise((resolve,reject) => {
//假如异步处理失败,返回失败的数据
reject('reject1');
})
.then(
value => {
console.log('promise2-->接收到promise1的数据为: ' + value);
//默认: return undefined ---》返回新的promise状态为rejected且value为undefined
}
)
.then(
value => {
console.log('promise3-->接收到promise2的数据为:' + value);
}
)
.catch(
reason => {console.log('接收到失败:'+ reason);}
)
运行结果:
接收到失败:reject1
上面的代码相当于以下的形式:
//promise1
new Promise((resolve,reject) => {
//假如异步处理失败,返回失败的数据
reject('reject1');
})
.then(
value => {
console.log('promise2-->接收到promise1的数据为: ' + value);
//默认: return undefined
},
//处理失败的回调:抛出异常:返回新的promise的状态为:rejected且value为reject1
reason => {throw reason}
//或者也可以写成: return Promise.reject(reason); 目的都是返回一个promise状态为rejected且reason为reject1的新promise对象
)
.then(
value => {
console.log('promise3-->接收到promise2的数据为:' + value);
},
//同样,由于上一个then里面返回的promise状态是rejected且value为reject1,在这里执行失败的回调处理
reason => {throw reason}
)
.catch(
reason => {console.log('接收到失败:'+ reason);}
)
运行结果同上
中断promise链
/**
* 中断promise链??
* 说明:当使用promise链式调用时,在中间中断,不在调用后面的回调函数
* 方法:在回调函数中返回一个pending状态的promise对象
*/
正常不中断的情况下:
//promise1
new Promise((resolve,reject) => {
//假如异步任务处理成功
resolve('resolve1');
})
.then(
value => {
console.log('promise2-->接收到promise1的数据为: ' + value);
//默认: return undefined
return value;
}
)
.then(
value => {
console.log('promise3-->接收到promise2的数据为:' + value);
//默认: return undefined
}
)
.then(
value => {
console.log('promise4-->接收到promise3的数据为:' + value);
}
)
运行结果:
promise2–>接收到promise1的数据为: resolve1
promise3–>接收到promise2的数据为:resolve1
promise4–>接收到promise3的数据为:undefined
中断后的处理:
//promise1
new Promise((resolve,reject) => {
//假如异步任务处理成功
resolve('resolve1');
})
.then(
value => {
console.log('promise2-->接收到promise1的数据为: ' + value);
//默认: return undefined
return value;
}
)
.then(
value => {
//返回一个状态为pending的promise对象
return new Promise(() => {})
}
)
.then(
value => {
console.log('promise3-->接收到promise2的数据为:' + value);
}
)
.then(
value => {
console.log('promise4-->接收到promise3的数据为:' + value);
}
)
运行结果:
promise2–>接收到promise1的数据为: resolve1