Skip to content
Eugene Lazutkin edited this page Mar 16, 2016 · 2 revisions

promisify() is a convenience function for node.js. It converts callback-based functions to promise-returning functions. The latter is much easier to compose.

Typical asynchronous node.js function takes a callback function as its last argument. That callback function is assumed to take at least one argument — an error as its first argument:

asyncFun(arg1, arg2, function callback (error, x, y) {
  if (error) {
    // handle an error
  }
  // success: handle arguments
});

promisify() will convert this function into a promise-returning composable function:

var wrappedAsyncFun = promisify(asyncFun);
wrappedAsyncFun(arg1, arg2).then(
  function (value) { var x = value[0], y = value[1]; /*...*/ },
  function (error) { /*...*/ }
);

Accepted arguments

promisify() accepts arguments in a following order:

  • fn — a callback-based function to be wrapped. It is assumed to following the node.js convention described above.
  • context — an optional context object to be used when invoke a function above with apply().
  • resultIsArray — an optional Boolean flag on how to treat additional callback arguments:
    • true — return all arguments after the error as an array.
    • false — if we have a single argument after the error, return it as is. Otherwise return an array with the rest of arguments. This is the default.
  • Deferred — an optional deferred constructor to use internally for promises. It can be either Deferred or FastDeferred. If not specified (or falsy) the standard Promise will be used.