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.
do_thing(result=>console.log(result))// <- Here is already too late to change your mind. And you don't have access to `result` either.
constpromise=do_thing()if(logging)promise.then(result=>console.log(result))promise.then(result=>{/* still available here, without running `do_thing` twice */})
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 the await 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. The async annotation is just so that people are not confused why the function returns a Promise when called instead of what was actually passed to return statements in it.
Understanding that it's Promises underneath, and that each await stops the function and puts it in a queue tells us how we should optimize for good performance:
For example, we shouldn't await the same value multiple times where we can easily avoid it:
constvalue=awaitdo_thing()// fix for our example aboveif(logging)console.log(value)something_else(value)
But we shouldn't immediately await every Promise we get our hands on, because there might be more work we can spawn before we need the result!
consturls=['/a','/b','/c']asyncbad_fetch(){constresults=[]for(consturlofurls){constres=awaitfetch(url)constdata=awaitres.json()results.push(data.property)}returnresults}asyncgood_fetch(){constresults=[]// now we start all requests, as well as parsing of their data, before "yeeting" from the functionfor(constdataofawaitPromise.all(urls.map(url=>fetch(url).then(x=>x.json()))){results.push(data.property)}returnresults}
The same, but without then and push (previous was written to be similar to the bad example)
running <- so the body DID actually run synchronously on call
first catch over <- then things after the call
awaited catch <- and only in await we get the error
But this isn't always true for all Promise-returning functions!
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!