Skip to content

Instantly share code, notes, and snippets.

@not-an-aardvark
Last active March 24, 2017 18:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save not-an-aardvark/65384ca554694d45af9c to your computer and use it in GitHub Desktop.
Save not-an-aardvark/65384ca554694d45af9c to your computer and use it in GitHub Desktop.
async functions without a transpiler
var Promise = require('bluebird');
var examplePromise1 = Promise.delay(5000);
var examplePromise2 = Promise.delay(2000).return('myValue');
// the following two are equivalent:
// 1. Async function (ES7, only available with a transpiler)
var func = async function (arg1, arg2, arg3) {
await examplePromise1;
var value = await examplePromise2;
return value + ' some other string ' + (arg1 + arg2 + arg3);
}
// 2. Generator function (bluebird feature)
Promise.coroutine.addYieldHandler(Promise.resolve); // This line ensures that synchronous values can be yielded
var func2 = Promise.coroutine(function* (arg1, arg2, arg3) {
yield examplePromise1;
var value = yield examplePromise2;
return value + ' some other string ' + (arg1 + arg2 + arg3);
});
// ---
func(1, 2, 3).then(console.log); // prints 'myValue some other string 6' after 7 seconds
func2(1, 2, 3).then(console.log); // does the exact same thing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment