Created
January 31, 2017 22:32
-
-
Save dengjonathan/23fadf7c5c1852dff07e2aeb19a321bd to your computer and use it in GitHub Desktop.
Sequenced async calls using promises
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 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