Last active
August 29, 2015 14:25
-
-
Save thgreasi/781967a18ce2ff764eda to your computer and use it in GitHub Desktop.
sync vs async loop over
This file contains 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
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