Tuesday, October 31, 2017

Node.js Best Practices - Async

Async function allows you to write Promise based code as if it were synchronous. It was shipped with V8 Engine since the Version 7.6.

Define a function using the async keyword, then you can use the await keyword within the function's body.
async function app () {
...
await ...
}

Async function is called, it returns with a Promise. When it returns a value, the promise gets fulfilled.

Async function throws an error, if it's rejected

Simple Async function
const util = require('util')
const {file} = require('fs')
const fileAsync = util.promisify(readFile)
async function app () {
const content = await fileAsync('log')
return content
}
app()
.then(console.log)
.catch(console.error)

If your applications are using Promise, then you can use "await" your Promises, instead of chaining them.

Above example leverage Promise using Node.js build-in "util.promisify" and read the file asynchronously.

Promise Reject/Error Handling

In the newer version of Node.js, if Promise gets rejected it will bubble down to the Node.js process. Make sure you handled the "try-catch" block properly on your app.

const util = require('util')
async function app () {
try {
await new Promise((resolve, reject) => {
reject(new Error('error'))
})
} catch (err) {
// handle the error
}
}
app()
.then(console.log)
.catch(console.error)

No comments:

Post a Comment