Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Last active November 24, 2023 13:08
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 lejonmanen/700e0f787a7013dda2cf1ec49c3d0e6e to your computer and use it in GitHub Desktop.
Save lejonmanen/700e0f787a7013dda2cf1ec49c3d0e6e to your computer and use it in GitHub Desktop.
Sync vs async
// Option 1: use a promise directly
let data;
function itTakesTime1() {
return new Promise((resolve, reject) => {
/* do something that takes time and produces a value */
resolve(value)
})
}
itTakesTime1().then(result => { data = result })
// Option 2: use a promise indirectly
async function itTakesTime2() {
/* do something that takes time and produces a value */
return value
}
data = await itTakesTime2()
/*
async is "syntactic sugar" for promises. Both options do the same thing.
Whenever you use async/await in your code, JavaScript uses promises under the hood.
Here's a great explanation of promises: https://javascript.info/promise-basics
And here's an explanation of async/await: https://javascript.info/async-await
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment