Created
October 15, 2019 12:26
-
-
Save nielsbom/2e088e3b5d20cf697b5fbd4810a20e80 to your computer and use it in GitHub Desktop.
Example of how async JavaScript works with 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
const getRandomTimeOutInMs = () => Math.floor(Math.random() * 5000); | |
const apis = ["Facebook", "Twitter", "Instagram"]; | |
const start = () => { | |
apis.forEach(api => { | |
let currentApi = new Promise(function(resolve, reject) { | |
let timeout = getRandomTimeOutInMs(); | |
setTimeout(() => { | |
resolve(`The ${api} API took ${timeout} ms to respond.`); | |
}, timeout); | |
}); | |
currentApi.then(result => { | |
console.log(result); | |
}); | |
}); | |
}; | |
document.addEventListener("DOMContentLoaded", start); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More info on promises: https://javascript.info/promise-basics