Hemanth's Scribes

javascript

ES7 Async Await

Author Photo

Hemanth HM

Thumbnail

async/await of ES7 is one of my favorite proposals, that would for sure change the way we handle asynchronous code in JavaScript!

Promise Example

let p1 = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Promise 1 ');
    }, 30);
  });
}

let p2 = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Promise 2');
    }, 10);
  });
}

async function getVal() {
  var res1 = await p1();
  var res2 = await p2();
  return res1 + res2;
}

(async function() {
  var res = await getVal();
  console.log(res); // Promise 1 Promise 2
}());

## File System Example
javascript
var lieFS = require('lie-fs'); // Promisified FS

(async function() {
  var list = await fs.readdir('~/');
  console.log(list);
}());

## Chain Animation (From the Spec)
javascript
async function chainAnimationsAsync(elem, animations) {
  var ret = null;
  try {
    for (let anim in animations) {
      ret = await anim(elem);
    }
  } catch(e) {
    /* ignore and keep going */
  }
  return ret;
}

## Async Await Fetch
javascript
let data = await (await fetch(url)).json()

Do let me know if you have your own set, until then happy async/await!

#javascript#es7#async
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.