Skip to content

Instantly share code, notes, and snippets.

@zdychacek
Last active February 15, 2017 20:14
Show Gist options
  • Save zdychacek/266d095a14096d965f9a to your computer and use it in GitHub Desktop.
Save zdychacek/266d095a14096d965f9a to your computer and use it in GitHub Desktop.
function coPromise (genFun, ctx) {
return new Promise(function (resolve, reject) {
co(genFun).call(ctx, function (err, data) {
if (err) {
return reject(err);
}
resolve(data);
});
});
}
@zdychacek
Copy link
Author

Helper function for handling async operations using co module and ES6 promises.

e.g.

// @returns promise
function loadData () {
   return coPromise(function* () {
      var data1 = yield getData1();
      var result = null;

      try {
          result = yield getData2(data1);
      }
      catch (ex) {
          // this will reject promise
          throw new Error("Error while loading data.");
      }

      // this will resolve promise with value result
      return result;
   }, this);
}

// call function here
loadData()
   .then(function (data) {
       // do some stuff
   })
   .catch(function (err) {
       // handle error here
   });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment