medikoo/deferred

Questions about usage

kiinoo opened this issue · 2 comments

Hi, I think deferred is powerful though I haven't gotten familiar with it.
Looking through examples in the page, I still have 2 questions:

  • what kind of functions can be promisified? i.e. deferred.promisify(theFn) will work for what functions.
  • how can I create a promise or deferred with reject callback, e.g.
var deferred = require('deferred');

var delay = function (fn, timeout) {
    return function () {
        var d = deferred(), self = this, args = arguments;

        setTimeout(function () {
            if(someValidation){ // <!-----------here only some validation succeeded, I will resolve it -->
              d.resolve(fn.apply(self, args));
            } else {
              d.reject(err); // <!-----------is there a the reject function? seems I could not found it... -->
            }
        }, timeout);

        return d.promise;
    };
};

anyone could help? thanks very much!

@kiinoo Promisify is made for asynchronous functions, so we can easily make them speak with promises.
Asynchronous function by convention takes callback as last argument and callback when called takes eventual error as first argument which is followed by success arguments. Asynchronicity in Node.js API stands on asynchronous functions which work that way.

Promise is rejected when it's resolved with an error object (instance of Error), there's no separate construct for that, you just do: d.resolve(new Error("Something went wrong")) and promise is rejected.

@medikoo thanks very much! I will have a try!