understanding-async-await

When writing code for the web, eventually you’ll need to do some process that might take a few moments to complete. JavaScript can’t really multitask, so we’ll need a way to handle those long-running processes.

Async/Await is a way to handle this type of time-based sequencing. It’s especially great for when you need to make some sort of network request and then work with the resulting data. Let’s dig in!

Promise? Promise.

Async/Await is a type of Promise. Promises in JavaScript are objects that can have multiple states (kind of like the real-life ones ☺️). Promises do this because sometimes what we ask for isn’t available immediately, and we’ll need to be able to detect what state it is in.

Consider someone asks you to promise to do something for them, like help them move. There is the initial state, where they have asked. But you haven’t fulfilled your promise to them until you show up and help them move. If you cancel your plans, you rejected the promise.

Similarly, the three possible states for a promise in JavaScript are:

  • pending: when you first call a promise and it’s unknown what it will return.
  • fulfilled: meaning that the operation completed successfully
  • rejected: the operation failed

Here’s an example of a promise in these states:

Here is the fulfilled state. We store a promise called getSomeTacos, passing in the resolve and reject parameters. We tell the promise it is resolved, and that allows us to then console log two more times.

const getSomeTacos = new Promise((resolve, reject) => {
  console.log("Initial state: Excuse me can I have some tacos");

  resolve();
})
  .then(() => {
    console.log("Order some tacos");
  })
  .then(() => {
    console.log("Here are your tacos");
  })
  .catch(err => {
    console.error("Nope! No tacos for you.");
  });
> Initial state: Excuse me can I have some tacos
> Order some tacos
> Here are your tacos

See the Pen


Promise States
by Sarah Drasner (@sdras)


on CodePen.

If we choose the rejected state, we’ll do the same function but reject it this time. Now what will be printed to the console is the Initial State and the catch error:

const getSomeTacos = new Promise((resolve, reject) => {
  console.log("Initial state: Excuse me can I have some tacos");

  reject();
})
  .then(() => {
    console.log("Order some tacos");
  })
  .then(() => {
    console.log("Here are your tacos");
  })
  .catch(err => {
    console.error("Nope! No tacos for you.");
  });
> Initial state: Excuse me can I have some tacos
> Nope! No tacos for you.

And when we select the pending state, we’ll simply console.log what we stored, getSomeTacos. This will print out a pending state because that’s the state the promise is in when we logged it!

console.log(getSomeTacos)
> Initial state: Excuse me can I have some ?s
> Promise {}
> Order some ?s
> Here are your ?s

What then?

But here’s a part that was confusing to me at first. To get a value out of a promise, you have to use .then() or something that returns the resolution of your promise. This makes sense if you think about it, because you need to capture what it will eventually be — rather than what it initially is — because it will be in that pending state initially. That’s why we saw it print out Promise {} when we logged the promise above. Nothing had resolved yet at that point in the execution.

Async/Await is really syntactic sugar on top of those promises you just saw. Here’s a small example of how I might use it along with a promise to schedule multiple executions.

async function tacos() {
  return await Promise.resolve("Now and then I get to eat delicious tacos!")
};

tacos().then(console.log)

Or a more in-depth example:

// this is the function we want to schedule. it's a promise.
const addOne = (x) => {
  return new Promise(resolve => {
    setTimeout(() => { 
      console.log(`I added one! Now it's ${x   1}.`)
      resolve()
    }, 2000);
  })
}

// we will immediately log the first one, 
// then the addOne promise will run, taking 2 seconds
// then the final console.log will fire
async function addAsync() {
  console.log('I have 10')
  await addOne(10)
  console.log(`Now I'm done!`)
}

addAsync()
> I have 10
> I added one! Now it's 11.
> Now I'm done!

See the Pen


Async Example 1
by Sarah Drasner (@sdras)


on CodePen.

One thing (a)waits for another

One common use of Async/Await is to use it to chain multiple asynchronous calls. Here, we’ll fetch some JSON that we’ll use to pass into our next fetch call to figure out what type of thing we want to fetch from the second API. In our case, we want to access some programming jokes, but we first need to find out from a different API what type of quote we want.

The first JSON file looks like this- we want the type of quote to be random:

{
  "type": "random"
}

The second API will return something that looks like this, given that random query parameter we just got:

{
  "_id":"5a933f6f8e7b510004cba4c2",
  "en":"For all its power, the computer is a harsh taskmaster. Its programs must be correct, and what we wish to say must be said accurately in every detail.",
  "author":"Alan Perlis",
  "id":"5a933f6f8e7b510004cba4c2"
}

We call the async function then let it wait to go retrieve the first .json file before it fetches data from the API. Once that happens, we can do something with that response, like add it to our page.

async function getQuote() {
  // get the type of quote from one fetch call, everything else waits for this to finish
  let quoteTypeResponse = await fetch(`https://s3-us-west-2.amazonaws.com/s.cdpn.io/28963/quotes.json`)
  let quoteType = await quoteTypeResponse.json()

    // use what we got from the first call in the second call to an API, everything else waits for this to finish
  let quoteResponse = await fetch("https://programming-quotes-api.herokuapp.com/quotes/"   quoteType.type)
  let quote = await quoteResponse.json()

  // finish up
  console.log('done')
}

We can even simplify this using template literals and arrow functions:

async function getQuote() {
  // get the type of quote from one fetch call, everything else waits for this to finish
  let quoteType = await fetch(`quotes.json`).then(res => res.json())

    // use what we got from the first call in the second call to an API, everything else waits for this to finish
  let quote = await fetch(`programming-quotes.com/${quoteType.type}`).then(res => res.json())

  // finish up
  console.log('done')
}

getQuote()

Here is an animated explanation of this process.

See the Pen


Animated Description of Async Await
by Sarah Drasner (@sdras)


on CodePen.

Try, Catch, Finally

Eventually we’ll want to add error states to this process. We have handy try, catch, and finally blocks for this.

try {
  // I’ll try to execute some code for you
}
catch(error) {
  // I’ll handle any errors in that process
} 
finally {
  // I’ll fire either way
}

Let’s restructure the code above to use this syntax and catch any errors.

async function getQuote() {
  try {
    // get the type of quote from one fetch call, everything else waits for this to finish
    let quoteType = await fetch(`quotes.json`).then(res => res.json())

      // use what we got from the first call in the second call to an API, everything else waits for this to finish
    let quote = await fetch(`programming-quotes.com/${quoteType.type}`).then(res => res.json())

    // finish up
    console.log('done')
  }

  catch(error) {
    console.warn(`We have an error here: ${error}`)
  }
}

getQuote()

We didn’t use finally here because we don’t always need it. It is a block that will always fire whether it is successful or fails. Consider using finally any time you’re duplicating things in both try and catch. I usually use this for some cleanup. I wrote an article about this, if you’re curious to know more.

You might eventually want more sophisticated error handling, such as a way to cancel an async function. There is, unfortunately, no way to do this natively, but thankfully, Kyle Simpson created a library called CAF that can help.

Further Reading

It’s common for explanations of Async/Await to begin with callbacks, then promises, and use those explanations to frame Async/Await. Since Async/Await is well-supported these days, we didn’t walk through all of these steps. It’s still pretty good background, especially if you need to maintain older codebases. Here are some of my favorite resources out there:

96 comments

  1. Link exchange is nothing else except it is simply placing
    the other person’s weblog link on your page at suitable place
    and other person will also do similar in support of you.

  2. It’s actually a great and helpful piece of information. I
    am satisfied that you just shared this useful information with
    us. Please keep us informed like this. Thanks for sharing.

  3. I feel this is one of the such a lot important information for me.

    And i’m satisfied reading your article. But should statement on few common things, The website taste
    is ideal, the articles is in reality excellent
    : D. Just right activity, cheers

  4. I don’t know whether it’s just me or if perhaps everybody else experiencing
    problems with your website. It looks like some of the text within your content are running off the screen. Can someone else please provide feedback and let me know if
    this is happening to them as well? This might be a issue with
    my internet browser because I’ve had this happen before.
    Thank you

  5. I have been exploring for a bit for any high-quality articles or weblog posts on this kind
    of area . Exploring in Yahoo I eventually stumbled upon this site.
    Reading this information So i am glad to exhibit that I have
    a very excellent uncanny feeling I discovered exactly what I
    needed. I most no doubt will make certain to do not put out of your mind this website and provides it a glance regularly.

  6. We’re a bunch of volunteers and starting a new scheme in our
    community. Your site offered us with valuable information to work
    on. You have done a formidable job and our entire group
    will likely be grateful to you.

  7. This design is wicked! You most certainly know how to keep a reader
    entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Great job.

    I really enjoyed what you had to say, and more than that, how you presented it.
    Too cool!

  8. Hi there! I know this is kinda off topic but I was wondering which
    blog platform are you using for this website? I’m getting
    fed up of WordPress because I’ve had problems
    with hackers and I’m looking at options for another platform.
    I would be great if you could point me in the direction of a
    good platform.

  9. I don’t even know how I stopped up here, however I
    believed this publish used to be good. I do not understand who you’re but definitely you are going to a famous blogger for those who
    are not already. Cheers!

  10. fantastic submit, very informative. I ponder
    why the opposite specialists of this sector don’t realize this.
    You should proceed your writing. I’m confident, you’ve a huge readers’ base already!

  11. Can I simply just say what a comfort to uncover a person that truly knows what they are
    talking about online. You actually know how to bring a problem to light and make it important.

    More people really need to read this and understand this side of your story.
    It’s surprising you are not more popular since you definitely have the gift.

  12. Hey There. I found your weblog the use of msn. That is a really neatly written article.
    I’ll make sure to bookmark it and come back to read extra of your useful
    information. Thank you for the post. I will definitely return.

  13. Ahaa, its good conversation about this paragraph here at this webpage, I have read all that, so at this time me also commenting here.

  14. Please let me know if you’re looking for a author for your weblog.
    You have some really great posts and I feel I would be a
    good asset. If you ever want to take some of the load off, I’d love to write some articles for your blog in exchange for a link back to mine.
    Please send me an e-mail if interested. Many thanks!

  15. I always used to study article in news papers but now as I am a user of net so
    from now I am using net for articles, thanks to web.

  16. Greate pieces. Keep posting such kind of information on your blog.
    Im really impressed by your site.
    Hello there, You’ve done an excellent job. I will certainly
    digg it and in my view suggest to my friends. I am sure they’ll be benefited from
    this website.

  17. I’ll right away seize your rss as I can not to find your email subscription hyperlink or newsletter
    service. Do you’ve any? Kindly permit me recognise so that I could
    subscribe. Thanks.

  18. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get four e-mails with the same comment.
    Is there any way you can remove me from that service? Thank you!

  19. Hi, Neat post. There’s a problem together with your web site in web explorer,
    could test this? IE nonetheless is the marketplace leader and a good component to folks will pass
    over your fantastic writing because of this problem.

  20. Hi, I do believe this is an excellent website. I stumbledupon it 😉 I’m going to revisit once again since I
    book-marked it. Money and freedom is the best way to change, may
    you be rich and continue to guide others.

  21. With havin so much written content do you ever run into any issues of plagorism or copyright
    violation? My website has a lot of unique content I’ve either created myself
    or outsourced but it seems a lot of it is popping it up all over the internet without my authorization. Do you know any
    solutions to help prevent content from being ripped off? I’d
    truly appreciate it.

  22. certainly like your website however you have to take a look
    at the spelling on quite a few of your posts. Many of them are
    rife with spelling problems and I to find it very troublesome to inform the truth nevertheless I’ll certainly come back again.

  23. Great blog here! Also your website loads up very fast!
    What web host are you using? Can I get your affiliate
    link to your host? I wish my web site loaded up as quickly as
    yours lol

  24. Hi I am so excited I found your website, I really found you by mistake, while I was looking on Askjeeve for something else, Nonetheless I am here now and would just like to say thanks a lot for a
    marvelous post and a all round enjoyable blog (I also love the theme/design), I don’t have time to go through it all at the moment
    but I have saved it and also added in your RSS feeds, so when I have time I will be back to read a great
    deal more, Please do keep up the excellent work.

  25. Does your blog have a contact page? I’m having a tough time locating it
    but, I’d like to send you an email. I’ve got some creative
    ideas for your blog you might be interested in hearing. Either way, great
    site and I look forward to seeing it grow over time.

  26. I every time used to read post in news papers but now as I am
    a user of net so from now I am using net for articles or reviews,
    thanks to web.

  27. Hello there I am so grateful I found your blog page, I really found you by accident,
    while I was browsing on Aol for something else, Nonetheless I am here
    now and would just like to say thanks a lot for a incredible post and
    a all round interesting blog (I also love the theme/design), I don’t have time to browse
    it all at the moment but I have bookmarked it and also included your RSS feeds, so when I have time I will be back
    to read more, Please do keep up the superb b.

  28. Howdy, I believe your blog might be having internet browser
    compatibility problems. Whenever I look at your website in Safari, it looks fine however,
    when opening in IE, it has some overlapping issues. I just wanted to provide you with a quick heads up!
    Besides that, great website!

  29. Hi my loved one! I wish to say that this post is amazing, nice
    written and include almost all significant infos. I would like to
    look extra posts like this .

  30. I’m really enjoying the theme/design of your web site. Do you ever run into
    any browser compatibility problems? A couple of my blog audience have complained about my website not working correctly in Explorer but looks great in Firefox.
    Do you have any advice to help fix this issue?

  31. After exploring a few of the blog articles on your blog, I honestly appreciate your way of blogging.
    I book-marked it to my bookmark webpage list and will be checking
    back soon. Please visit my website as well and let me know your opinion.

  32. A motivating discussion is definitely worth comment. I believe that you should publish more on this issue, it might not be a taboo matter
    but usually people do not talk about such topics.
    To the next! Cheers!!

  33. You actually make it seem really easy with your presentation but I find this topic to be really something
    that I feel I would never understand. It seems too complex and very large
    for me. I’m having a look ahead to your next post, I’ll try to get the cling of
    it!

  34. The other day, while I was at work, my cousin stole
    my iPad and tested to see if it can survive a 30 foot drop, just
    so she can be a youtube sensation. My iPad
    is now broken and she has 83 views. I know this is totally off
    topic but I had to share it with someone!

  35. Heya i’m for the first time here. I found this board
    and I find It really useful & it helped
    me out much. I hope to give something back and aid others like you aided me.

  36. naturally like your website however you need to test the spelling on quite a few of your posts.
    A number of them are rife with spelling problems and I in finding it very troublesome to inform the reality however I’ll surely come again again.

  37. Unquestionably consider that that you stated. Your favorite reason appeared to
    be on the web the easiest thing to be mindful of. I say to you, I definitely get annoyed at
    the same time as other folks consider issues that they just don’t understand about.
    You managed to hit the nail upon the highest as smartly as outlined out the entire thing with no need side effect ,
    other folks can take a signal. Will likely be back to get more.
    Thanks

  38. I have been exploring for a little bit for any high quality articles or
    weblog posts in this sort of house . Exploring in Yahoo I at last stumbled upon this site.

    Studying this info So i am satisfied to express that I’ve an incredibly good uncanny feeling I found out just what
    I needed. I so much unquestionably will make certain to don?t disregard
    this web site and give it a look on a constant basis.

  39. That is a great tip especially to those new to the blogosphere.

    Simple but very accurate information… Thank you for sharing this one.
    A must read post!

  40. Its like you read my mind! You appear to know a lot about this, like
    you wrote the book in it or something. I think that you could do
    with some pics to drive the message home a bit, but instead of that, this is excellent blog.
    An excellent read. I’ll certainly be back.

  41. When someone writes an post he/she maintains the plan of a user in his/her
    brain that how a user can be aware of it. So that’s why this post is great.

    Thanks!

  42. you’re in reality a just right webmaster. The web
    site loading speed is incredible. It seems that you’re doing any distinctive trick.
    Furthermore, The contents are masterwork. you have done a magnificent task
    in this matter!

Leave a Reply

Your email address will not be published.