myword

Extending ES6 Promises

myword

Extending ES6 promises...

Jake Archibald released a great polyfill of ES6 Promises that I've been trying to migrate towards using:

https://github.com/jakearchibald/es6-promise

When contrasted with something like Q (https://github.com/kriskowal/q), ES6 Promises lacks a lot of the bells and whistles that Q has built up. This project serves as a place to extend ES6 promises with some of those bells and whistles.

npm install myword

This method provides a simple means for one to extend the Promise prototype

 
  var Promise = require('myword');
 
  // mixin the ability to add a delay to your promise chain (don't ask me why you would do that...) 
  Promise.mixin({
    delayfunction(milliseconds) {
      return function(result) {
        return new Promise(function(resolvereject) {
          setTimeout(function() {
            resolve(result);
          }, milliseconds);
        };
      };
    }
  });
 
  // assuming getSomething() returns a promise and doSomething() does something with the result 
  getSomething()
    .delay(1000)
    .then(doSomething);
 

This method converts existing node-style functions that take callbacks into ones that return a Promise

var Promise = require('myword');
 
/**
 * where callback is of the signature function(err, result)
 */
var typicalNodeMethod = function(namecallback) {
  callback("Hello, " + name + "!");
};
 
var promiseMethod = Promise.promisify(typicalNodeMethod);
 
promiseMethod("Claire")
  .then(console.log);
 

This method will be invoked when a promise is resolved or rejected. Function will be resolved with the resolved result or the error from being rejected.

This method will flatten (or spread) a promise result that is an array into individual function parameters

var Promise = require('myword');
 
// return a promise to resolve with a user (typically via an async db call or something) 
var getUser = function(name) {
  return Promise.resolve({name: name});
}
 
Promise.all([getUser("James"), getUser("Lindsay"), 2007])
  .spread(function(husbandwifeyear) {
    console.log(husband.name + " married " + wife.name + " in " + year);
  });
 

In contrast, normally by using promise.then() you would code the following:

 
Promise.all([getUser("James"), getUser("Lindsay"), 2007])
  .then(function(result) {
    console.log(result[0].name + " married " + result[1].name + " in " + result[2]);
  });