Refactoring: returning a promise from a value or an existing promise

前端 未结 1 601
迷失自我
迷失自我 2021-01-22 08:09

My scenario

I used to have some node.js implementation done using callbacks but I am now refactoring my code to use Promises ins

相关标签:
1条回答
  • 2021-01-22 09:09

    I see only two problems.

    1. If you want to explicitly return a rejected promise with a value, you should do that with Q.reject.

    2. Calling .done() on promise means that the promise ends there. It cannot be chained further.

    So, your code would look like this

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

    Now, the update function just returns a promise always. Its up to the callers to attach the success or failure handlers to it.

    0 讨论(0)
提交回复
热议问题