Please. Been trying to find a clear explanation as to why Async/Await > Promises or so lots of devs say.
For further actions, you may consider blocking this person and/or reporting abuse
Please. Been trying to find a clear explanation as to why Async/Await > Promises or so lots of devs say.
For further actions, you may consider blocking this person and/or reporting abuse
... -
Anwar Hossain -
Amaresh Adak -
Gladiators Battle -
Top comments (24)
JavaScript, by design, is not multithreaded. So unlike your operating system, it can't do two things at once.
However, there are times we need to wait for stuff to come back from the server. In this case, JavaScript can ask the browser to do the work and be notified when that work is done
This is asynchronous programming - having something done in the background and getting notified when it's done.
Originally, we did this with callbacks - so we'd say "hey browser, please do this work, and when you're done, here's a function you can call with the results"
The problem with callbacks is that we often have to do a few things in the background (asynchronously), so the code starts to get difficult to understand, with many layers of nested callbacks.
Along came the promise, which meant that our code could flatten out a bit. Callback code like this:
Could be a little simpler:
(EDIT: as noted below, the code above has a bug; I'm not going to remove it, because that would invalidate comments below, but do check out fixes for this code, as shown below!)
Which was a little easier to read and write (and error handling was neater, with
.catch()
)async/await
is a nice way that modern JavaScript let's us use promises with even less code and nesting:And you can use try/catch to handle errors.
Under the hood, helpers like Babel and TypeScript translate the code above into a version a lot like the promises version, using an old, clever JavaScript feature called generator functions. Don't worry about it too much now though (:
Hope this helps. Apologies for any typos - I'm doing this from my phone.
Edit: Sorry I didn't see the example above the flattened one which is the same as one of my versions.
Your promise example has a bug but it's a really good example where async/await shines over promises.
result1
isn't accessible in the finalthen
. With promises you lose the simplicity of the.then
chain if you want both the first return value and to use it as a trigger for a follow-up request.These are some ways to do it with promises.
With async/await, as Davyd has shown above, you have a single scope. No workarounds are needed.
Nice catch. I could hardly see all the text on my phone when I was typing. Was bound to have at least one glaring flaw (:
Now, I'm at a pc, I think I'd probably correct to:
(assuming I can use short notation for objects in this particular js-world)
And I think that illustrates even better why async/await is a win (:
I have a reputation to uphold here: stackoverflow.com/a/1638961/31899 So let me give it a shot. Ahem! :)
I am your faithful dog JS. I love you with all my heart, but normally when you go off to school. I go do other stuff. I find React the cat and bark at him. That's fun because he's getting really old. I nap. I eat. I drive the dreaded "mail man" away from our house. Then, when you get home again, we play! Hooray!
But today, you said, "Await me and I will give you this bone." So I have not moved. I am a good dog. I am a very good dog. I will stay here and not do anything else until you get back and then I will get the bone and we will play!
That, is Async/Await for a five year old.
Love it! :D
LMAO I love this!!!
After many discussions about it, I've come to the conclusion that people prefer
async/await
over promises because they don't want to do function composition and want to write synchronous imperative code.There's a time and a place for everything.
I'll throw my hat into the ring.
Let's say you're running a race, and there are water stations set up along the way. You can keep running down the main path, or hop off to the side to one of the water stations. Some of them have lines, and you have to wait your turn before you can get water and go back to the main path. To
await
means to be one of the people waiting in line, because you're *wait*ing for the person in front of you to finish what they're doing. For a minute, the two runners are joined together and can only go as fast as the first of them. Waiting in line makes it so that other people can queue up behind us (we have to be markedasync
, which means other people canawait
us before we canawait
someone else).In terms of code, this makes it much cleaner and straightforward, as I think Davyd has demonstrated.
Because async/await is actually one level higher than
Promise
. An async function is not aPromise
but a() => Promise
. In other words, an async function is a lazyPromise
.Note that we kind of hit a dead-end above. Even though we've created
p0
to store the Promise, we cannot rerunp0
. The most we can do is attach morethen
s. We cannot cancel it either.We still cannot cancel it, but at least we can rerun it.
A more detailed explanation can be found in the Wiki of Fluture.
Async/Await is syntactic sugar around promises.
So think of them like the same thing.
The two can also be used intertwined, E.g. one might use Promise.all to wait for two async functions to return in parallel.
A
Promise
is a "handle" to a value that may or may not already be available.It's better than a callback, because you can start the asynchronous process first, and think about what you will do with the outcome of it later.
but what is
await
? It allows you to wait until the value of a promise is available within synchronous-looking code, with all the usual imperative constructs.How is this achieved? When you execute "await", your function pauses, and allows other things to run.
Then, when the awaited result is ready, the function continues execution from that point onward, as if "await" was just a function that took a long time.
Think of it like the code before the
await
and the code after theawait
are two separate functions, just keeping the same variable scope.That's why it can only be used in
async
functions: since the function doesn't "finish" (return the actual value and end forever) when called, but later, it also must return a Promise. Theasync
annotation is just so that people are not confused why the function returns a Promise when called instead of what was actually passed toreturn
statements in it.Understanding that it's
Promise
s underneath, and that eachawait
stops the function and puts it in a queue tells us how we should optimize for good performance:The same, but without
then
andpush
(previous was written to be similar to the bad example)Gotchas
All
throw
s in a function markedasync
are rejections, never throws from the initial function call.This outputs
But this isn't always true for all Promise-returning functions!
Promises and async functions are like you're code is a hard worker. But it has too much to do by itself so it says to it's useless coworker sitting doing nothing "do this and come back to me with the results while I carry on with this"
Await is when your code needs the result from that so you say await that result.
Side note. If it's JavaScript you can only call await inside an async function.
So if you have this code (from Davyd above)
Does the code wait until result1 is set and then continue with result2 or does it just make both calls and wait until both are ready?
the code waits until result1 is set and just then continue to result2.
if you want to wait for them both to complete and then continue your code you need to use
await Promise.all([result1, result2])
Async:
Promise:
Imagine you drop a pillow, that pillow falls, right?
Then imagine if you make that pillow async and in the middle of it you say await, the pillow stops in the middle of the air and you can do something else like change the pillow cover, only when you are done, the pillow continues falling.
Some comments may only be visible to logged-in visitors. Sign in to view all comments.