Skip to content

Instantly share code, notes, and snippets.

@ryaninvents
Created June 20, 2015 21:15
Show Gist options
  • Save ryaninvents/eae2eeaf68cb82bf93e3 to your computer and use it in GitHub Desktop.
Save ryaninvents/eae2eeaf68cb82bf93e3 to your computer and use it in GitHub Desktop.
Generator functions and promises

A quick demonstration of how Promises work with generator functions in ES6.

$ npm i
$ node_modules/.bin/babel-node promise-test.js

Output:

imaGenerator started
imaPromise started
imaPromise finished
resolving
imaGenerator yielding
ok
{
"name": "promise-test",
"version": "1.0.0",
"description": "",
"main": "promise-test.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel": "^5.5.8",
"co": "^4.5.4"
}
}
import {co} from 'co';
function imaPromise() {
console.log('imaPromise started');
const p = new Promise(
function (resolve, reject) {
setTimeout(function () {
console.log('resolving');
resolve('ok');
}, 1000);
}
);
console.log('imaPromise finished');
return p;
}
function *imaGenerator() {
console.log('imaGenerator started');
const v = yield imaPromise();
console.log('imaGenerator yielding');
return v;
}
co(function *() {
const result = yield imaGenerator();
console.log(result);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment