ES6+ | promise正确的链式表达

前言

使用promise进行异步操作的同步表达,可以解决过往使用回调函数导致的回调地狱。
但是在实际场景下,有时候由于开发人员理解不深入,会错误地把promise写成回调的模样。
本文以setTimeout代表异步操作,本质模拟的是多步连续调用HTTP服务的实际场景。

let counter = 1;
function asyncAction() {
  let p = new Promise(function(resolve, reject) {
    // 异步
    setTimeout(function() {
      resolve(counter++);
    }, 0);
  });
  return p;
}

错误的回调写法

promise 错用回调的情况,在执行then中直接调用下一个promise异步方法。

asyncAction().then(res => {
  console.log(res);
  asyncAction().then(res=>{
    console.log(res);
    asyncAction().then(res=>{
      console.log(res);
    })
  })
});

链式写法

promise 实现真正的链式异步操作时,每一步then以后应该return新的promise。

asyncAction()
  .then(res => {
    console.log(res);
    return asyncAction();
  })
  .then(res => {
    console.log(res);
    return asyncAction();
  })
  .then(res => {
    console.log(res);
  });

仓库

实验代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值