COMP6080

Web Front-End Programming

Javascript - Async

Await

 

Credit to Simon Haddad for being a key part of preparing this lecture

Await / Async

Whilst promises are an improvement from callbacks, they can still create unnecessarily verbose code for trying to use async code synchronously in simple ways.

 

So a new syntax was created in ES2017 (now supported by virtually all browsers) to help this.

 

Await / Async

const fs = require('fs').promises;

const readFiles = async () => {
  let data = '';
  try {
    data = await fs.readFile('chapter1.txt', 'utf-8');
    console.log('Chapter 1: ', data);
  } catch (err) {
    console.log('Error: ', err);
  }
};

readFiles();
const fs = require('fs').promises;

const files1 = fs.readFile('chapter1.txt', 'utf-8')
files1
  .then(data => {
    console.log('Chapter 1: ', data);
  })
  .catch(err => {
    console.log('Error: ', err);
  });

This is a very basic comparison of the two in action.

Await / Async

const fs = require('fs').promises;

const readFiles = async () => {
  let data = '';
  try {
    data = await fs.readFile('chapter1.txt', 'utf-8');
    console.log(data);
    data = await fs.readFile('chapter2.txt', 'utf-8');
    console.log(data);
    data = await fs.readFile('chapter3.txt', 'utf-8');
    console.log(data);
    data = await fs.readFile('chapter4.txt', 'utf-8');
    console.log(data);
    data = await fs.readFile('chapter5.txt', 'utf-8');
    console.log(data);
  } catch (err) {
    console.log(err);
  }
};

readFiles();
const fs = require('fs').promises;

const files1 = fs.readFile('chapter1.txt', 'utf-8')
files1
  .then(data => {
    console.log('Chapter 1: ', data);
    return fs.readFile('chapter2.txt', 'utf-8')
  })
  .then(data => {
    console.log('Chapter 2: ', data);
    return fs.readFile('chapter3.txt', 'utf-8')
  })
  .then(data => {
    console.log('Chapter 3: ', data);
    return fs.readFile('chapter4.txt', 'utf-8')
  })
  .then(data => {
    console.log('Chapter 4: ', data);
    return fs.readFile('chapter5.txt', 'utf-8')
  })
  .then(data => {
    console.log('Chapter 5: ', data);
  })
  .catch(err => {
    console.log('Error: ', err);
  });

The benefit of async/await becomes more noticeable when doing substantially more async calls that you want to process linearly.

Feedback

COMP6080 22T1 - Async - Await

By haydensmith

COMP6080 22T1 - Async - Await

  • 390