Last active
March 24, 2017 18:43
-
-
Save not-an-aardvark/65384ca554694d45af9c to your computer and use it in GitHub Desktop.
async functions without a transpiler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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