Promise 只处理失败的回调

代码

var A = new Promise(function (resolve, reject) {
  console.log('do sth.');
  setTimeout(() => {
    console.log('~~~~~');
    //        resolve('ok');
    reject('error ******');
    console.log('+++++');
  }, 3000); // 延时3秒执行一次结束
});

//    var B = A.then()  //穿透
var B = A.then(undefined, reason => {
  // 只处理失败
  console.log(222, reason);
  return 'A.then.error';
});
setInterval(() => {
  console.log(A);
  console.log(B);
  console.log('~~~~~~~~~~~~~~~~~~~~');
}, 1000);
console.log('===================');

效果

root@ubuntu:~/workspace/es6/babel# node dist/index.js 
Debugger attached.
do sth.
===================
Promise { <pending> }
Promise { <pending> }
~~~~~~~~~~~~~~~~~~~~
Promise { <pending> }
Promise { <pending> }
~~~~~~~~~~~~~~~~~~~~
~~~~~
+++++
222 error ******
Promise { <rejected> 'error ******' }
Promise { 'A.then.error' }
~~~~~~~~~~~~~~~~~~~~
Promise { <rejected> 'error ******' }
Promise { 'A.then.error' }
~~~~~~~~~~~~~~~~~~~~
Promise { <rejected> 'error ******' }
Promise { 'A.then.error' }
~~~~~~~~~~~~~~~~~~~~
^C
``
posted @ 2022-10-18 11:27  flytoyou  阅读(35)  评论(0编辑  收藏  举报