Since we've been going over Promise
's in the latest posts, I think it's a good time to bring up async
/await
. Promise
's open up asynchronous programming, and async
/await
make asynchronous programming even easier to compose. Under the hood aync
/await
is syntactic sugar giving us an easier way to layout our asynchronous code.
async function timer () { const process = new Promise((res) => { setTimeout(() => { res('Some process that takes a while') }, 1000) }) const processOutput = await process console.log(processOutput) // logs 'Some process that takes a while' after waiting 1 second } timer()
Console:
From this first example, you can see that we create a new Promise
just like before, but this time, instead of using .then
with a callback to retrieve the resolved value, we can now await
the Promise
. This means that we can assign the resolved value to a new const
instead of being stuck in the scope of a callback function
.
async function runTimer() { const timer = async () => new Promise((res) => { setTimeout(() => { res('this took 1 second') }, 1000) }) console.log('before awaiting') const timerOutput = await timer() console.log(timerOutput) console.log('after awaiting') } runTimer()
Console:
Here is a slightly more usable example with a bit more to explain. Instead of creating a new Promise
immediately, this time we we create a function
that we can then invoke when we want to await
it. The big key here is the keyword async
, if you prepend this keyword to a function, you are now able to call await
on it. It is key to note that when you add async
to a function, that function now returns a Promise
, that is the way that await
is now able to be used. So in this example we are returning a Promise
so that we are able to resolve
it later and get the resolved value.
So far these Promise
and async
/await
examples how shown the very basics. Up next we will start exploring fetch
so we can see how all these different concepts all tie together. Until then, get out there and start async
/await
ing everything!