Skip to content

Instantly share code, notes, and snippets.

@DarinDev1000
Last active June 7, 2019 21:40
Show Gist options
  • Save DarinDev1000/2db1eec6191d7c0566bab49a1f6d9d6d to your computer and use it in GitHub Desktop.
Save DarinDev1000/2db1eec6191d7c0566bab49a1f6d9d6d to your computer and use it in GitHub Desktop.
// This page demonstrates running multiple functions simultaneously
// and waiting on them to finish.
// Maybe you have an api call that takes 6 seconds...
// And you only need the response at the end
// Would you like to start a function and check if the promise is resolved later?
// Then check out the async/await and the promiseAll functions
main();
// Launches 3 types of functions
async function main() {
await synchronousFunctions();
await asyncAwait();
await promiseDotAll();
}
// Synchronous (normal) Functions
async function synchronousFunctions() {
const startTime = Date.now()
console.log("----------- Synchronous (normal) Functions -----------")
const message = await longFunction();
await someOtherFunction();
console.log("Awaited Message: ", message);
console.log(`took: ${Date.now() - startTime} ms`);
}
// With promise and await
async function asyncAwait() {
const startTime = Date.now()
console.log("----------- With async / await -----------")
const asyncPromise = longFunction();
// Put consecutive code here
// Code that can run while longFunction() is running
someOtherFunction();
// ...
// Now wait for the first function
const message = await asyncPromise;
console.log("Awaited Message: ", message);
console.log(`took: ${Date.now() - startTime} ms`);
}
// With Promise.all()
async function promiseDotAll() {
const startTime = Date.now()
console.log("----------- With Promise.all() -----------")
Promise.all(
[longFunction(),
someOtherFunction()])
.then((response) => {
console.log("Awaited Message: ", response[0]);
console.log(`took: ${Date.now() - startTime} ms`);
});
}
// ---- Helper FUnctions ----
// Function that may take a while
async function longFunction() {
console.log("Started longFunction()");
await sleep(6000);
console.log("Finished longFunction()");
return "Message Returned"
}
// Function you can do while waiting
async function someOtherFunction() {
console.log("Started someOtherFunction()");
await sleep(4000);
//...
console.log("Finished someOtherFunction()");
}
// Sleep this long
function sleep(ms){
return new Promise(resolve=>{
setTimeout(resolve,ms)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment