ES2017 Goodness: await and async
Along with ES2017, came a bunch of new options to manage asynchronous methods better. While not all developers, especially non-nodeJS ones have taken note of those, many of us have gotten into the habbit of using boilerplate code when needed, without really understanding how they work.
So here's a small overview that can help you out.
Async and await
Both of these keywords work with promises. The await keyword simply put pauses the flow of a function until a promises is resolved and throws an error if the promise resolution fails
Let's assume there's a function that returns a promise. That does something
var promiser = function(){
return new Promise(function(resolve,reject){
doSomething((err,data)=>{
if(err) return reject(err);
return resolve(data)
})
})
}
The typically method of handling this would be to define then and catch callbacks
promiser().then((data)=> { doSomethingElse(data)} ).catch((err)=>{//Oops})
What await allows you to do is achieve a synchrnous sort of flow (and avoid callback hell
var data = await promiser;
doSomethingElse(data)
So what this does is it waits for the promise to resolve and returns the data it would provide
You failed me
What about failure? Well, await will simply throw an exception when it fails and you can catch it
try{
var data = await promiser;
doSomethingElse(data);
}catch(ex){
//Destroy all records. Launch nuke attack
}
There is a catch (no pun intended). Await can only be use in a method that is async. So what is this async thing and why is it important?
async function dodo(){
var data = await promiser();
}
If you try await in a non async function, your interpreter will act up and tell you how wrong you are, maybe even call you names.
Async
Async simply marks that a function returns a promise. So an async function must always return a promise. This tells the interpreter that the function will do promisey stuff such as await, etc.
What if the function doesn't return anything?
The interpreter will simply create a new promise inside of it and return that. If the function returns a non promise such as integer, it will be wrapped up so that that it returns a promise that resolves to the value that is returned?
^^ Exremely confusing line ^^
So let me explain this with a little bit of code
function dodo(){
return 3;
}
dodo() // returns the value 3
async function dodo(){
return 3;
}
is equivalent to
async function dodo(){
return new Promise(function(resolve,reject){ resolve(3)})
}
``
So async effectively wraps up the whole thing in a promise
If an async function has a bunch of await keywords, its a wise idea to use await whenever it is invoked. So let's look at another
async function queryTheWeatherAndUpdateCache(city){
var weather = await queryWeather(city);
await updateCache(weather);
return weather;
}
async function anotherFunction(){
var weather= queryTheWeatherAndUpdateCache();// This is wrong since it will simply return the promise
var weather = await queryTheWeatherAndUpdateCache();
}
Even if** it didn't return anything** , you'd still have to use await to ensure the function was done executing. OR if you don't care about the result of the query, just continue.
Parallel stuff?
What if you don't need to do everything serially? What if you wanted to do some stuff parallelly and someother stuff serially. Well, you can use Promise.all
What if you need to fetch the weather and text your friend while at the same time
async function queryTheWeatherAndUpdateCacheAndTextMyFriend(city){
var weather = await queryWeather(city);
await Promise.all( [updateCache(weather),textMyFriend(weather) ]);
//This runs the first function, waits for the promise and then executes the two parallelly. In case you're curious, the returned value is all of the resolved values in order
return weather;
}
async anotherFunction(){
var weather= queryTheWeatherAndUpdateCache();// This is wrong since it will simply return the promise
var weather = await queryTheWeatherAndUpdateCache();
}
IF you need more help with promises, please feel free to set a session up with me :)
Also you can comment here in case you have any questions, or Ive made any mistakes
awesome work.