Async/Await

This is one of the latest additions to Node.js, having been added early in 2017 with version 7.6, providing an even better way of writing asynchronous code, making it look and behave a little more like synchronous code.

Going back to our file reading example, say you wanted to get the contents of two files and concatenate them in order. This is how you can achieve that with async/await:

const fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);
async function readFiles()
{
const content1 = await readFile(`${__dirname}/../temp/sample1.txt`);
const content2 = await readFile(`${__dirname}/../temp/sample2.txt`);
return content1 + ' - and - ' + content2;
}
readFiles().then(result => console.log(result));

In summary, any asynchronous function that returns a promise can be awaited.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset