Slides Link

http://bit.ly/aaw-wut

echo `whoami`

Ahsan Ayaz

Software Architect

Wait!!

Async

Await

Call it out Loud!

What is async await?

Your first encounter with async JS. Probably.


function getUsers() {
    let users;
    fetch('https://randomuser.me/api/')
        .then(response => response.json())
        .then(responseData => {
          users = responseData.results;
        });
    
    return users;
}

const data = getUsers();
console.log(data);
// undefined

Let's talk about Promises

Bob

asks for a pen

Josh

had a pen. gives to bob

But let's have a Sync story first

  • Straight deal
  • No waiting time
  • Synchronous execution

A story full of promises

Bob

asks for a pen

Josh

promised to give when he would get one

Bob

Ana

asks for the math's book

gives bob the book

Bob

receives a pen from somewhere

sends to bob

function main() {
  let borrowedPen, borrowedMathsBook;
  getPenFromJosh()
    .then((pen) => {
      borrowedPen = pen;
      console.log(borrowedPen);
      // {ink: 'blue', brand: 'dux'}
    })
  borrowedMathsBook = getMathsBookFromAna();
  console.log(borrowedMathsBook);
  // {title: 'Intro to Maths', author: 'Famous Author'}
}
function getPenFromJosh() {
  return new Promise((resolve) => {
    const pen = {ink: 'blue', brand: 'dux'};
    setTimeout(() => {
      resolve(pen);
    }, 2000);
  });
}

function getMathsBookFromAna() {
  return {title: 'Intro to Maths', author: 'Famous Author'};
}

Why Promises?

To Avoid Callback Hell

Better code readability


var user;

function getUser() {  
    return fetch('https://randomuser.me/api/')
        .then(response => response.json());
}

getUser()
    .then(userResp => {
        user = userResp;        
        // do something with the user now 
    });

Promises can be chained

var user, events, firstEventFollowers;
getUser()
    .then(userResp => {
        user = userResp;       
        // a function that returns a promise 
        return getUserEvents();
    })
    .then(eventsResp => {
        events = eventsResp;
        // a function that returns a promise
        return getFirstEventFollowers(event.id);
    })
    .then(firstEventFResp => {
        firstEventFollowers = firstEventFResp;
        console.log('all done. I is happy');
    })

Better error handling in promises


var user, events, firstEventFollowers;
getUser()
    .then(userResp => {
        user = userResp;       
        // a function that returns a promise 
        return getUserEvents();
    })
    .then(eventsResp => {
        events = eventsResp;
        // a function that returns a promise
        return getFirstEventFollowers(event.id);
    })
    .then(firstEventFResp => {
        firstEventFollowers = firstEventFResp;
        console.log('all done. I is happy');
    })
    .catch(err => {
        console.log('An error occurred in fetching the data');
        console.log(err.message);
    });

Executing parallel calls


var organizations, events;

var promises = Promise.all([
    getEvents(),  // returns a promise
    getOrganizations() // returns a promise
]);


promises
    .then(([eventsResp, orgsResp]) => {
        // when all the promises are resolved 
        organizations = orgsResp;
        events = eventsResp;
    })
    .catch(err => {
        console.log('An error occurred in fetching the data');
        console.log(err.message);
    });

Async Await

A syntactic sugar over promises. Introduced in ES7

Implementation

// Promises
function main() {
    var user, events, firstEventFollowers;
    getUser()
        .then(userResp => {
            user = userResp;        
            // a function that returns a promise
            return getUserEvents(user.id);
        })
        .then(eventsResp => {
            events = eventsResp;
            // a function that returns a promise
            return getFirstEventFollowers(event.id);
        })
        .then(firstEventFResp => {
            firstEventFollowers = firstEventFResp;
            console.log('all done. me happys');
        })
        .catch(err => {
            console.log('Could not fetch stargazers');
            console.log(err.message);
        });
}





// Async Await
async function main() {
    const user = await getUser();
    const events = await getUserEvents(user.id);
    const firstEventFollowers = await getFirstEventFollowers(event.id);
}

Catching Errors

Catching Errors

async function main() {
    try {
        const user = await getUser();
        const events = await getUserEvents(user.id);
        const firstEventFollowers = await getFirstEventFollowers(event.id);
        consr something = "test"; // syntax error here
    }
    catch (e) {
        console.log(e);
    }
}

function getUser() {
   return fetch('https://someurl')
    .then(resp => resp.json_());  // there's an error here. i.e. `json_`
}

The try catch will catch both errors within main or within any of the async function calls within main

Parallel Async Calls

Parallel Async Calls

async function main() {
    try {
        const [users, events, organizations] = await Promise.all([
          getUsers(),            // returns a promise
          getEvents(),           // returns a promise
          getOrganizations()     // returns a promise
        ]);
        
        console.log('events', events);
        console.log('users', users);
        console.log('organizations', organizations);
    }
    catch (e) {
        console.log(e);
    }
}

function getUsers() {
   return fetch('https://someurl/users')
    .then(resp => resp.json());
}

Who wants to see a quick demo?

Questions?

Thank You !

Software Architect

Modus Create

Async Await. Wait wut?

By Ahsan Ayaz

Async Await. Wait wut?

This is a talk based on Async Await introduced in ES7 for JavaScript. Goes around different examples and usage where they appear most beneficial.

  • 681
Loading comments...

More from Ahsan Ayaz