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); | |
| }); |