Last active
January 31, 2016 02:53
-
-
Save teone/9f0d82f4f1bbcc338544 to your computer and use it in GitHub Desktop.
Async Loop With Generators and Promises
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
| 'use strict'; | |
| // async function (eg: rest call) | |
| const makeRequest = function (endpoint) { | |
| return new Promise(function (resolve, reject) { | |
| resolve(endpoint); | |
| }); | |
| } | |
| // generator function | |
| // iterates over an array and call several time the async function | |
| const generator = function* (resources) { | |
| for(let endpoint of resources){ | |
| let foo = yield makeRequest(endpoint); | |
| console.log(foo); | |
| } | |
| }; | |
| // Instantiate the generator, | |
| // call next passing the value when the promise has been resolved, | |
| // untill the generator has completed, then return the last promise value, | |
| const run = function(generator, resources) { | |
| var it = generator(resources); | |
| function go(res){ | |
| // if the generator has ended return the value | |
| if(res.done){ | |
| return res.value; | |
| } | |
| //else wait for promise and call generators.next() | |
| return res.value | |
| .then((res) => { | |
| go(it.next(res)); | |
| }) | |
| .catch((e) => { | |
| it.throw(e); | |
| }); | |
| } | |
| go(it.next()); | |
| } | |
| // execution | |
| const resources = ['endpont1', 'endpoint2', 'endpoint3']; | |
| run(generator, resources); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment