Promise.prototype.catch(): 是.then(null, rejection)的别名,用于指定发生错误时的回调函数
p.then( (val) -> console.log('fulfilled:', val)).catch( (err) => console.log('rejected', err));// 等同于
p.then( (val) => console.log('fulfilled:', val)).then(null, (err) => console.log("rejected:", err));// catch方法可以捕获then方法中抛出的错误
var promise = new Promise(function (resolve, reject) {throw nuw Error('test');
});
promise.catch(function (error) {console.log(error);
});
// 如果Promise状态已经变成Resolved, 再抛出错误是无效的.
var promise = new Promise(function (resolve, reject) {resolve('ok');throw new Error('test from promise');
});
promise.then(function (value) { console.log(value) }).catch(function (error) { console.log(error) });
// 如果没有使用catch方法指定错误处理的回调函数,Promise对象抛出的错误不会传递到外层代码
var someAsyncThing = function() {return new Promise (function (resolve, reject) {resolve(x + 2);});
};someAsyncThing().then(function() {console.log('everything is great');
});// 注:resolve(x + 2) 会报错,x未定义, 控制台也确实报错了,但并不会终止这个脚本,即这个脚本再服务器内执行的退出码为0
参考《ES6标准入门》(第3版) P280~P282