Skip to content

Instantly share code, notes, and snippets.

@nielsbom
Created October 15, 2019 12:26
Show Gist options
  • Save nielsbom/2e088e3b5d20cf697b5fbd4810a20e80 to your computer and use it in GitHub Desktop.
Save nielsbom/2e088e3b5d20cf697b5fbd4810a20e80 to your computer and use it in GitHub Desktop.
Example of how async JavaScript works with promises
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);
@nielsbom
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment