TIL ELI5 for Async Await
POSTED ON:
TAGS: javascript eli5
tl;dr:
- Javascript is single-threaded.
- If you make a call to a friend across the world, it'll take 20 seconds before they respond. You can't just wait 20 seconds. So you run other code.
- Async/Await is a setup to allow you to 'await' on a result until it comes back.
- Then when it's ready, it'll execute the rest of the code.
- Async/Await and Promises are the same, but written differently.
- Async/Await uses then() format, which is functional programming style.
- Promises pass data to a variable, which is more the imperative format.
via bonanzaguy:
Imagine you need to call your bank for some reason or another. As always, you get a message telling you that they're experience higher than average call volume. At this point, one of two things can happen: 1) you sit there on hold doing nothing else because you don't want to miss the rep when they finally answer, or 2) the automated system offers to call you back when a rep is available, and you hang up and go do other stuff.
Option 1 is synchronous, which is how code will run by default. For example:
function doTheThing() {
const data = reallyLongRunningFunction(); // Program is stuck waiting for this line
// do something with data
}
Option 2 is asynchronous:
async function doTheThingAsync() {
const data = await reallyLongRunningFunctionAsync(); // Program can go do other stuff while this finishes
// do something with data
}
So just like in our analogy where we are stuck waiting on the phone for the agent to pick up, synchronous code executes line by line and can't move to the next line or do anything else until the previous line of code is done executing. An async function, on the other hand, allows us to context switch. In the analogy, you hang up the phone and go do dishes or whatever while waiting for them to call you back. Your program is able to do exactly the same thing--when it hits a line marked with await inside an async function, the program is able to execute code somewhere else while it's waiting for the awaited function to finish, and then when it does it will resume executing where it left off.
What about promises? #
via aeveltstra
.then(f)
is for Function Composition. It is part of the functional programming paradigm. It is a way to kick off the next step in a series of steps.
With promises, it is possible to pass the promise result into the "thenned" function.
In imperative programming you would capture the result of a promise, and throw that into a follow-up function.
Which you choose is a matter of personal preference: javascript can do either.
Related TILs
Tagged: javascript