在Q中学习承诺和例外与拒绝 [英] Learning promises and exceptions vs. rejecting in Q

查看:92
本文介绍了在Q中学习承诺和例外与拒绝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的印象是,promise中的异常会触发后续的失败处理程序,但我在这段代码中没有看到它:

I'm under the impression that an exception inside a promise will trigger the subsequent fail-handler, but I'm not seeing it happen in this code:

var Q = require('q');

function x() {
  console.log('x');
  var deferred = Q.defer();

  setTimeout(
      function() {
        console.log('resolving x');
        deferred.resolve('hi');
      },
      1000
  );

  return deferred.promise;
}

function y() {
  console.log('y');
  var deferred = Q.defer();

  setTimeout(
      function() {
        console.log('throwing in y');
        throw new Error('Oih!');
      },
      1000
  );

  return deferred.promise;
}

x().then(y).then(
    function () {
      console.log('yes');
    },
    function () {
      console.log('no');
    }
);

我做错了什么,或者我误解了?

Am I doing something wrong, or have I misunderstood?

推荐答案

你正在混合回调和承诺+你有一个延迟反模式的情况。使用 Q.delay 或包装如:

You are mixing callbacks and promises + you have a case of deferred anti-pattern. Either use Q.delay or a wrapper like:

function delay(ms) {
    var d = Q.defer();
    setTimeout(d.resolve, ms);
    return d.promise;
}

现在有超时的promise API,没有理由使用setTimeout :

Now that there is promise API for timeouts, there is no reason to use setTimeout:

function x() {
    return delay(1000).then(function () {
        console.log("hi");
    });
}

function y() {
    return delay(1000).then(function () {
        console.log('throwing in y');
        throw new Error('Oih!');
    });
}

使用:

x()
.then(y)
.then(function() {
    console.log('yes');
})
.catch(function(e) {
     console.log('no');
});

这篇关于在Q中学习承诺和例外与拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆