Skip to content

Instantly share code, notes, and snippets.

@dmorosinotto
Last active November 6, 2015 20:59
Show Gist options
  • Save dmorosinotto/bba1599fa7a84fc9eedb to your computer and use it in GitHub Desktop.
Save dmorosinotto/bba1599fa7a84fc9eedb to your computer and use it in GitHub Desktop.
function getFile(file) {
return new Promise(
(resolve,reject) => {
if (Math.random()>0.3) fakeAjax(file,resolve);
else reject('SOMETHING GO WRONG WITH '+file);
}
);
}
function Async(gen){
const it = gen(); //get iteretor from Genereator
return step(Promise.resolve(it.next())); //start "state machine" step into 1st yield gen
function step(p){
//here P is a promise that is resolved with then value of then next iteration it.next()->{value:Promise done:boolean}
return p.then(s => { //s: {done: boolean, value: Promise}
if (s.done) return s.value; //if iteretor finish, stop recursion and return last value returned
//else use s.value (that is a promise yielded in the gen) and get the value out of the promise (r) and push back r to the itererator
return step(s.value.then(r => it.next(r) // (send r-> result of yield in the iterator) and recursive advance another step
,e => it.throw(e) )); // (if promise has error propagate to generator)
});
}
}
function* Run(){
var p1 = getFile("file1");
var p2 = getFile("file2");
var p3 = getFile("file3");
output ( yield p1 );
output ( yield p2 );
output ( yield p3 );
return "Complete Run request Parallel, print in Sequence!";
}
//RUN PARALLEL REQUEST, SEQUENTIAL PRINT
Async(Run).then(output).catch(showerr);
// **************************************
function fakeAjax(url,cb) {
var fake_responses = {
"file1": "The first text",
"file2": "The middle text",
"file3": "The last text"
};
var randomDelay = (Math.round(Math.random() * 1E4) % 8000) + 1000;
console.log("Requesting: " + url);
setTimeout(function(){
cb(fake_responses[url]);
},randomDelay);
}
function output(text) {
console.log(text);
}
function showerr(err) {
console.error(err);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment