Created
March 1, 2017 19:33
-
-
Save gregglind/fd7fe546281793578c1b7e43e393b2ef to your computer and use it in GitHub Desktop.
Promises, and loading the files
This file contains hidden or 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 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