javascript – Promises:.done()总是执行,即使.catch()是?

前端之家收集整理的这篇文章主要介绍了javascript – Promises:.done()总是执行,即使.catch()是?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的承诺问题

我是Promises的新手,我一直在阅读Q Documentation,它说:

When you get to the end of a chain of promises,you should either return the last promise or end the chain.

我在我的代码中使用Q.Promise方式定义了一个Promise,使用以下console.logs来注销执行跟踪:

function foo(){
   return Q.Promise(function(resolve,reject) {

    doSomething()
    .then(function() {
      console.log('1');
      return doSomething1();
    })
    .then(function() {
      console.log('2');
      return doSomething2();
    })
    .then(function() {
      console.log('3');
      return doSomething3();
    })
    .catch(function(err) {
      console.log('catch!!');
      reject(err);
    })
    .done(function() {
      console.log('done!!');
      resolve();
    });

  });
}

如果每个doSomethingN()都正确执行,一切都按预期工作,我得到预期的跟踪:

1
2
3
done!!

但是如果任何doSomethingN()失败:

foo()正常工作,因为错误函数回调是每当发生拒绝(错误)时运行的回调:

foo().then(function(){/ * * /},function(err){/ * this runs!* /});

我得到以下跟踪(即doSomething1()失败时):

1
catch!!
done!!

我的问题

我一开始的想法是:

Okay,let’s handle the chaining success and failure in both: .done() and .catch() methods. If everything goes well .done()‘s callback will be executed and the promise will be resolved. In case there’s an error at any point,.catch()‘s callback will be executed and the promise will be rejected – and because of that,done() won’t be executed.

我想我错过了.done()的工作方式…因为通过查看我的日志记录,我意识到.done()似乎总是在执行 – 是否有错误和.catch()是否被执行 – 这就是我没想到的.

所以,在那之后,我删除了.done()的回调,现在foo():

>如果在链执行期间出现错误,则有效
>如果一切正常,则不起作用

我应该重新考虑什么,我应该如何/应该让它发挥作用?

解决方法

你应该考虑这样做:
function foo() {
  // Calling .then() on a promise still return a promise.
  // You don't need Q.Promise here
  return doSomething()
    .then(function(doSomethingResult) {
      console.log('1');
      return doSomething1();
    })
    .then(function(doSomething1Result) {
      console.log('2');
      return doSomething2();
    })
    .then(function(doSomething2Result) {
      console.log('3');
      return doSomething3();
    });
}



foo()
  .then(function(fooResult) {
    console.log(fooResult); // fooResult should be what is returned by doSomething3()
  })
  .catch(function(err) {
    console.error(err); // Can be thrown by any 
  })
  .done(function() {
    console.log('I am always executed! error or success');
  });

如果你想返回一个promise,在大多数情况下使用catch没有多大意义(除非你想恢复潜在的错误).在返回promise的方法中使用done是没有意义的.您宁愿在链的最后使用这些方法.

请注意,doSomethingX()可以返回值或promise,它将起作用.

原文链接:https://www.f2er.com/js/150126.html

猜你在找的JavaScript相关文章