Skip to content

Instantly share code, notes, and snippets.

@gregglind
Created March 1, 2017 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregglind/fd7fe546281793578c1b7e43e393b2ef to your computer and use it in GitHub Desktop.
Save gregglind/fd7fe546281793578c1b7e43e393b2ef to your computer and use it in GitHub Desktop.
Promises, and loading the files
function waitUp(t) {
window.setTimeout(()=>console.log("waited", t),t)
}
waitUp.bind(null, 100)()
function loadAFile(url) {
return new Promise(function (resolve, reject){
// simulate unknown wait time
var delay = 1000*Math.random();
window.setTimeout(function () {
console.log('loaded', url);
resolve();
}, delay);
// in the true one, you would call
// resolve from the onComplete, or such
})
}
var log = {
done: function () {console.log(Date.now(), "done")}
};
console.log("// this will wait until after load");
loadAFile('some.url').then(log.done);
function loadEmAll (names) {
let promises = names.map(function (fn) {return loadAFile(fn)});
return Promise.all(promises);
}
var fileNames = ['url1', 'url2', 'url3'];
loadEmAll(fileNames).then(log.done);
// or simpler!
Promise.all(fileNames.map(function (fn) {return loadAFile(fn)})).then(log.done);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment