es6 --- > Promise.catch

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值