Skip to content

Instantly share code, notes, and snippets.

@dengjonathan
Created January 31, 2017 22:32
Show Gist options
  • Save dengjonathan/23fadf7c5c1852dff07e2aeb19a321bd to your computer and use it in GitHub Desktop.
Save dengjonathan/23fadf7c5c1852dff07e2aeb19a321bd to your computer and use it in GitHub Desktop.
Sequenced async calls using promises
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);
}
// **************************************
// The old-n-busted callback way
function getFile(file) {
return new Promise(function(resolve){
fakeAjax(file,resolve);
});
}
// Request all files at once in
// "parallel" via `getFile(..)`.
//
// Render as each one finishes,
// but only once previous rendering
// is done.
['file1', 'file2', 'file3'].map(getFile)
.reduce((master, promise) => master.then(() => promise).then(output),
Promise.resolve());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment