Last active
November 24, 2023 13:08
-
-
Save lejonmanen/700e0f787a7013dda2cf1ec49c3d0e6e to your computer and use it in GitHub Desktop.
Sync vs async
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
// 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