JavaScript Promises, await and async - Part 2

First post in this series

So what about await and async? The await keyword lets you make code wait for a promise to end. For example:

await myPromiseFunction();
// Code after promise resolves

For security reasons, you can’t have await anywhere. You need to wrap it in an async function. There are to ways to do this:

async function myAsyncFunction(){
   await myPromiseFunction();
   // Code after promise resolves
}
myAsyncFunction();
// Or:
(async function(){
   await myPromiseFunction();
   // Code after promise resolves
})();

Examples

First, let’s extend the timer example from yesterday with await.

  1. Put the wait code in a function
    function wait(){
    var myPromise = new Promise(function (resolve,reject){
    setTimeout(function (){
    resolve("Timer finished!");
    },1000);
    });
    return myPromise;
    }
    
  2. Create an async function
    function wait(){
    var myPromise = new Promise(function (resolve,reject){
    setTimeout(function (){
    resolve("Timer finished!");
    },1000);
    });
    return myPromise;
    }
    async function myAsyncFunction(){
    // More code goes here
    }
    
  3. Add an await statement
    function wait(){
    var myPromise = new Promise(function (resolve,reject){
    setTimeout(function (){
    resolve("Timer finished!");
    },1000);
    });
    return myPromise;
    }
    async function myAsyncFunction(){
    await wait();
    }
    
  4. Add console messages and call the function
    function wait(){
    var myPromise = new Promise(function (resolve,reject){
    setTimeout(function (){
    resolve("Timer finished!");
    },1000);
    });
    return myPromise;
    }
    async function myAsyncFunction(){
    console.log("timer started");
    await wait();
    console.log("timer ended");
    }
    myAsyncFunction();
    

    Fetch Example

    Promises aren’t just for timers. The fetch method uses promises, and we can use await and async with it.

  5. Create a fetch call
    fetch("https://kyleplo.github.io/myTextFile.txt")
    .then(function (r){
       return r.text()
    });
    
  6. Add await and wrap with async
    async function myAsyncFunction(){
    var r = await fetch("https://kyleplo.github.io/myTextFile.txt")
       .then(function (r){
          return r.text()
       });
    }
    
  7. Add a call and show the result
    async function myAsyncFunction(){
    var r = await fetch("https://kyleplo.github.io/myTextFile.txt")
       .then(function (r){
          return r.text()
       });
    console.log(r);
    }
    myAsyncFunction();
    
Written on July 22, 2018

In the categories:

javascript promises

View all my posts: somerandomcharactersthatwillgetpickedupbysearchengines