重构:从值或现有承诺返回承诺

时间:2015-11-27 02:21:19

标签: javascript node.js promise q

我的场景

我曾经使用node.js完成了一些callbacks实施,但我现在正在重构我的代码以使用Promises - 使用Q模块。我有以下update()函数,其中内部_update()函数已返回Promise

exports.update = function(id, template, callback) {
  if (!_isValid(template)){
    return callback(new Error('Invalid data', Error.INVALID_DATA));
  }

  _update(id, template) // this already returns a promise
  .then(function() {
    console.log('UPDATE was OK!');
    callback();
  }, function(err) {
    console.log('UPDATE with ERRORs!');
    callback(err);
  });
};

我的问题

我想实现类似以下内容

exports.update = function(id, template) {
  if (!_isValid(template)){
    // how could I make it return a valid Promise Error?
    return reject(new Error('Invalid data', Error.INVALID_DATA));
  }

  return _update(id, template) // return the promise
  .done();
};

由于_update()已经返回promise,我猜这种方式改变就足够了(不会吗?):

  return _update(id, template)
  .done();

而且......如果condition中的if-clause等于true怎么办?我怎么能重构

return callback(new Error('Invalid data', BaboonError.INVALID_DATA));

抛出error以避免将callback传递给update()并处理该错误(或者错误可能会返回_update())?

另外,请致电update()

myModule.update(someId, someTemplate)
.then(function() { /* if the promise returned ok, let's do something */ })
.catch(function(err) { /* wish to handle errors here if there was any */});

我的代码中的其他地方:

  • 如果在promise传播过程中出现错误 - 它应该处理它,
  • 或者,如果没有错误 - 它应该做其他一些事情

我接近我所期待的吗?我怎么能最终实现呢?

1 个答案:

答案 0 :(得分:3)

我只看到两个问题。

  1. 如果您希望使用值显式返回被拒绝的承诺,则应使用Q.reject执行此操作。

  2. 在promise上调用.done()意味着承诺在那里结束。它无法进一步链接。

  3. 所以,你的代码看起来像这样

    exports.update = function (id, template) {
      if (!_isValid(template)) {
        return Q.reject(new Error('Invalid data', Error.INVALID_DATA));
      }
    
      return _update(id, template);
    };
    

    现在,update函数只返回一个承诺。由呼叫者将成功或失败处理程序附加到其上。