Thursday, 9 August 2018

async/await in node.js

Async await is a syntax that makes your asynchronous code look more like synchronous code, it is basically some nice syntactic sugar built on top of Promises.

You just add the async keyword to your function and or expression and that method will now return a promise! You can then use the await keyword to get the result of the promise!

One thing to note is await can only be used inside of an async function, so if you want to execute the code just in a file you need to wrap it in a self-executing function.

I know what you're thinking, "This is great so I can stop writing those weird promises now right?", well no. Though you can quickly create synchronous-looking code that returns promises in either resolved or rejected state.

This does not allow for the handling of asynchronous code that is not promise based inside of your function.

Unfortunately, this will not work as the function will just return a promise that has undefined or no value. To get around this we need to wrap our callback code in a promise as before.

This can now be used in an async function!

You can also make good use of util.promisify to help you with this!

Just remember it will only work for functions where the parameters match the node pattern of callback last and the callback starts with the error.

You can see in this case that by defining our callback method to the node standard util.promisify happily wraps it in a promise.

In this case, I removed the parameter passed to doTest() this results in a "TypeError: callback is not a function" error being thrown, which will be very confusing if you didn't write the callback code you are wrapping and it doesn't have very good error messages.

More on async/await soon!

No comments:

Post a Comment