Today I Learned - Rocky Kev

TIL ELI5 for Async Await

POSTED ON:

TAGS:

tl;dr:

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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.