详解Promise的链式写法

详细解释了Promise为什么可以用链式的写法,讲解了then,catch方法返回了什么
摘要由CSDN通过智能技术生成

我们知道Promise对象具有then,catch等方法,在执行这些方法之后,也会返回一个Promise对象,正因为如此,Promise对象才有链式写法。规则如下:

对于then方法,1.如果then方法里面的回调函数没有返回值,并且也没有抛出错误,那么该then方法返回的Promise对象的状态为fulfilled,其value为undefined;

var p = new Promise(function (resolve, reject) {
  resolve(555);
});
p.then(function (value) {
  console.log(value);
}).then(function (res) {
  console.log(res);
  console.log(666);
});

打印结果如下:

2.如果回调函数抛出了错误,那么该then方法返回的Promise对象的状态为rejected,value为抛出的错误值。

var p = new Promise(function (resolve, reject) {
  resolve(555);
});
p.then(function () {
  throw "abc";
}).catch(function (res) {
  console.log(res);
});

打印结果如下:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值