Skip to content

Instantly share code, notes, and snippets.

@thgreasi
Last active August 29, 2015 14:25
Show Gist options
  • Save thgreasi/781967a18ce2ff764eda to your computer and use it in GitHub Desktop.
Save thgreasi/781967a18ce2ff764eda to your computer and use it in GitHub Desktop.
sync vs async loop over
function getParam(x) { }
function myFunc(argument) { }
function myAsyncFunc(argument) { return new Promise(function(resolve, reject) { /* ... */ }); }
//========== sync loop over
for (var i = 0; i < l; i++) {
try {
var result = myFunc(getParam(i));
console.log(result);
} catch (ex) {
console.error(ex);
}
}
console.log('TADA!');
//========== async loop over
asyncLooper().then(function() {
console.log('TADA!');
});
function asyncLooper() {
var promiseI = 0;
return control();
function control() {
if (promiseI < l) {
return handler(myAsyncFunc(getParam(promiseI)));
}
else {
return Promise.resolve();
}
}
function handler(crntPromise) {
return crntPromise
.then(function(result){
console.log(result);
}).catch(function(error){
console.error(error);
})
.then(function(){
promiseI++;
})
.then(function () {
return control();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment