a-brief-look-at-async-await

In this article, we will look into async-await. Let’s start with async functions.

From MDN:

The async function declaration defines an asynchronous function, which returns an AsyncFunction object. An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.

You can use the async keyword when implementing a function:

async function doSomething() {
 
}

Or with arrow functions:

const doSomething = async () => {

}

All async functions will always return a Promise. However, the await keyword allows you to wait for a promise to be resolved. Let’s begin with a simple example:

const addOne = function(number) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(number   1);
    }, 1000);
  });
};

const asyncFunction = async function() {
  const result = await addOne(1);
  console.log(result);
};

The code await addOne(1) will wait until the promise is resolved and return the 2, similar to:

const someFunction = function() {
  addOne(1).then((result) => console.log(result));
};

The await keyword can’t be used at top level code, yet, or in functions without async. Together async and await provide a great framework to write asynchronous code that is easy to understand.

Case

Let’s say; you are creating a webpage that allows users to sign documents. However, the documents need to be ready before the user can sign them. The webpage calls an endpoint that returns the current status of the document. Either true or false. If the API doesn’t return true within 30 seconds after loading the webpage, the user should be redirected to an error page.

How would you solve this using async-await? The first thing we need is a function that calls the API:

function check() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(get('/resource/check');
    }, 5000);
  });
}

This function waits 5 seconds before calling the API. Let’s move on to the async function:

async function waitAndCheck() {
  try {
    for (let i = 0; i < 6; i  ) {
      const status = await check();
      if (status) {
        
      }
    }
  } catch (error) {
    
  }
  
}

By making this function async, we solve the problem. The function waitAndCheck will only call the check function 6 times and will not execute longer than 30 seconds. This case could have been solved several ways, for example, we could chain check() like this:

function chain() {
  check()
    .then(result => {
      if (result) {
         
      }
      check()
        .then(result => {
          if (result) {
              
          }
          check()
            .then(result => {
              if (result) {
                 
              }
              check()
                .then(result => {
                  if (result) {
                    
                  }
                  check()
                    .then(result => {
                      if (result) {
                         
                      }

                      
                    })
                    .catch(error =>  
                })
                .catch(error =>  
            })
            .catch(error =>  
        })
        .catch(error =>  
    })
    .catch(error =>  
}

That’s all! I hope this inspires you to use async-await.

91 comments

  1. I got this site from my friend who shared with me regarding this site and
    now this time I am browsing this site and reading very informative articles or reviews
    at this time.

  2. Every weekend i used to go to see this web site, as i want enjoyment,
    since this this web page conations truly pleasant funny stuff
    too.

  3. Today, while I was at work, my sister stole my
    iPad and tested to see if it can survive a forty foot drop, just
    so she can be a youtube sensation. My apple ipad is now destroyed and she has 83 views.
    I know this is totally off topic but I had to share it with someone!

  4. Howdy! I could have sworn I’ve been to this website before but after checking through some of the
    post I realized it’s new to me. Anyways, I’m definitely happy I found it and
    I’ll be book-marking and checking back frequently!

  5. Nice 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 fast as yours lol

  6. It’s a pity you don’t have a donate button! I’d certainly donate to this outstanding blog!
    I guess for now i’ll settle for bookmarking and adding
    your RSS feed to my Google account. I look forward to
    fresh updates and will talk about this site with my Facebook group.

    Chat soon!

  7. My family members all the time say that I am killing my time here at net,
    but I know I am getting knowledge daily by reading such nice
    articles.

  8. Hi there! I just would like to give you a huge thumbs
    up for your great info you have here on this post.
    I am returning to your web site for more soon.

  9. Hey! I know this is somewhat off topic but I was wondering
    if you knew where I could find a captcha
    plugin for my comment form? I’m using the same blog platform as yours and I’m having difficulty finding
    one? Thanks a lot!

  10. Hello there I am so grateful I found your blog, I
    really found you by mistake, while I was researching on Askjeeve for something else, Nonetheless I am here now and would just like to say kudos for a remarkable post and a all round enjoyable blog (I also love the theme/design), I don’t have time to read it all at the minute but I have book-marked it and
    also added in your RSS feeds, so when I have time I will be back to read more,
    Please do keep up the fantastic work.

  11. You can certainly see your enthusiasm in the work you write.

    The world hopes for more passionate writers like you who are not afraid to
    mention how they believe. At all times follow
    your heart.

  12. Great beat ! I wish to apprentice while you amend your website, how could i subscribe for a
    blog website? The account helped me a appropriate deal.
    I have been a little bit familiar of this your broadcast
    provided brilliant transparent idea

  13. I have read so many posts regarding the blogger lovers but this paragraph is genuinely a
    nice post, keep it up.

  14. If some one desires expert view on the topic of blogging afterward i suggest him/her to go
    to see this weblog, Keep up the nice work.

  15. Great web site you have here.. It’s hard to find excellent writing like yours nowadays.

    I truly appreciate individuals like you! Take care!!

  16. I’ve been surfing on-line greater than 3 hours
    these days, yet I never discovered any fascinating article
    like yours. It is lovely value sufficient for me.
    Personally, if all website owners and bloggers made excellent content as you
    did, the net will probably be much more useful than ever before.

  17. Everyone loves what you guys tend to be up too.
    This type of clever work and exposure! Keep up the superb works guys I’ve you guys to blogroll.

  18. My relatives all the time say that I am wasting my time here at web, except
    I know I am getting familiarity daily by reading such nice content.

  19. I do accept as true with all of the ideas you have offered to your post.
    They’re very convincing and will definitely work. Still, the posts are too brief for newbies.

    Could you please lengthen them a little from subsequent time?
    Thanks for the post.

  20. Having read this I thought it was extremely informative.
    I appreciate you finding the time and energy to put this article together.
    I once again find myself personally spending a lot of
    time both reading and posting comments. But so what, it was still worth it!

  21. I am extremely impressed with your writing skills and also with the layout
    on your blog. Is this a paid theme or did you customize it yourself?
    Anyway keep up the excellent quality writing, it is rare to see a great blog
    like this one nowadays.

  22. Thanks for a marvelous posting! I seriously enjoyed reading it, you could
    be a great author. I will remember to bookmark your blog and will
    eventually come back later in life. I want to encourage continue your great job, have a nice evening!

  23. Unquestionably believe that which you stated.
    Your favorite reason seemed to be on the web the simplest thing to
    be aware of. I say to you, I definitely get irked while people
    think about worries that they just don’t know about.
    You managed to hit the nail upon the top and defined out the whole thing without having side-effects ,
    people can take a signal. Will likely be back to get more.
    Thanks

  24. Hey terrific website! Does running a blog such as
    this take a lot of work? I have virtually no expertise in programming however I had been hoping to
    start my own blog in the near future. Anyway, should you have any ideas or
    tips for new blog owners please share. I know this is off topic but I just had to ask.
    Cheers!

  25. Hi there to all, since I am really keen of reading this weblog’s post to be updated on a regular basis.
    It contains nice data.

  26. Fantastic post but I was wondering if you could write a litte more on this subject?
    I’d be very grateful if you could elaborate a little bit further.
    Thanks!

  27. I just like the valuable information you provide to
    your articles. I’ll bookmark your weblog and test again right here frequently.
    I’m fairly sure I’ll be told many new stuff right right here!
    Good luck for the next!

  28. I know this if off topic but I’m looking into starting my own blog and was curious what
    all is needed to get setup? I’m assuming having a blog like
    yours would cost a pretty penny? I’m not very internet
    savvy so I’m not 100% sure. Any recommendations or advice would be greatly appreciated.
    Thanks

  29. We’re a bunch of volunteers and starting a brand new scheme in our community.
    Your web site provided us with valuable info to work on. You have performed an impressive job and our whole community might be thankful to you.

  30. Great post. I was checking continuously this blog and I am impressed!
    Very helpful information specially the last part :
    ) I care for such information much. I was looking for this certain info for a long
    time. Thank you and best of luck.

  31. I loved as much as you’ll receive carried out right here.
    The sketch is attractive, your authored material stylish.
    nonetheless, you command get got an nervousness over that you wish
    be delivering the following. unwell unquestionably come
    further formerly again as exactly the same nearly a lot often inside case you shield this increase.

  32. Its such as you learn my mind! You appear to grasp a lot approximately this, such as you wrote the guide in it or something.
    I believe that you can do with a few p.c. to force the message home a bit, but instead of that, this is wonderful blog.
    An excellent read. I’ll definitely be back.

  33. I wanted to thank you for this great read!!
    I definitely loved every little bit of it. I have you book marked to look at new things you post…

  34. Hi there, I discovered your web site by means of Google whilst searching for a similar subject, your site got here up, it looks good.
    I’ve bookmarked it in my google bookmarks.
    Hi there, just become alert to your blog via Google, and located that
    it’s truly informative. I’m gonna watch out for brussels.

    I will appreciate if you proceed this in future.
    Numerous other folks can be benefited out of
    your writing. Cheers!

  35. Awesome website you have here but I was wondering if you knew of any discussion boards
    that cover the same topics talked about here? I’d really
    love to be a part of group where I can get responses from other knowledgeable people that share the same interest.
    If you have any suggestions, please let me know. Appreciate it!

  36. Thanks for sharing your thoughts. I really appreciate your efforts and I
    will be waiting for your next write ups thanks once again.

  37. Oh my goodness! Incredible article dude! Thanks,
    However I am going through problems with your RSS.
    I don’t know why I can’t subscribe to it.
    Is there anybody else getting similar RSS problems? Anyone who knows the solution will you kindly respond?
    Thanks!!

  38. Very nice post. I just stumbled upon your weblog and
    wished to say that I’ve really enjoyed browsing your blog posts.
    In any case I will be subscribing to your feed and I hope you write
    again soon!

  39. Hey! This is kind of off topic but I need some help from an established blog.
    Is it difficult to set up your own blog? I’m not very techincal but I can figure things out pretty quick.
    I’m thinking about creating my own but I’m not sure where to begin. Do
    you have any tips or suggestions? Thanks

  40. Hi there i am kavin, its my first time to commenting anywhere,
    when i read this post i thought i could also make comment due to this brilliant piece of writing.

  41. My programmer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using WordPress
    on several websites for about a year and am anxious about switching
    to another platform. I have heard fantastic things about blogengine.net.
    Is there a way I can import all my wordpress content into
    it? Any help would be really appreciated!

  42. Hey I know this is off topic but I was wondering if
    you knew of any widgets I could add to my blog that automatically tweet
    my newest twitter updates. I’ve been looking for a plug-in like this
    for quite some time and was hoping maybe you would have
    some experience with something like this. Please let me know if you run into anything.
    I truly enjoy reading your blog and I look forward to your new updates.

  43. It’s the best time to make a few plans for the future and it is time to be happy.
    I’ve learn this post and if I may just I wish to counsel you few fascinating things or tips.
    Perhaps you can write next articles relating to this article.
    I want to read even more issues about it!

  44. Hmm it appears like your blog ate my first comment (it was extremely long)
    so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your
    blog. I as well am an aspiring blog writer but I’m still new to the whole thing.

    Do you have any suggestions for beginner blog writers?

    I’d genuinely appreciate it.

  45. Hi would you mind stating which blog platform you’re using?
    I’m planning to start my own blog in the near future
    but I’m having a hard time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and
    style seems different then most blogs and I’m looking for something completely unique.
    P.S Apologies for getting off-topic but I had to ask!

  46. Write more, thats all I have to say. Literally, it seems as
    though you relied on the video to make your point. You clearly know
    what youre talking about, why waste your intelligence on just posting videos to your site when you could be giving us something
    enlightening to read?

  47. Howdy just wanted to give you a quick heads up. The text in your article seem to be running off
    the screen in Opera. I’m not sure if this is a format issue or something to do with internet browser
    compatibility but I figured I’d post to let you know.
    The design look great though! Hope you get the problem fixed soon.
    Kudos

  48. Wonderful blog! Do you have any tips and hints for aspiring writers?

    I’m hoping to start my own site soon but I’m a little lost on everything.
    Would you advise starting with a free platform like WordPress or go
    for a paid option? There are so many options out there that I’m totally confused ..
    Any tips? Thank you!

  49. I loved as much as you will receive carried out right here.

    The sketch is attractive, your authored subject matter stylish.
    nonetheless, you command get got an edginess over that you wish be delivering
    the following. unwell unquestionably come further formerly again as
    exactly the same nearly a lot often inside case you shield this increase.

  50. I was wondering if you ever thought of changing the page
    layout of your blog? Its very well written; I love what youve
    got to say. But maybe you could a little more in the way of content so people
    could connect with it better. Youve got an awful lot of text for only having 1 or two images.

    Maybe you could space it out better?

  51. Do you mind if I quote a couple of your articles
    as long as I provide credit and sources back to your site?
    My blog site is in the exact same niche as yours and my
    visitors would genuinely benefit from some of the information you provide here.
    Please let me know if this okay with you.

    Appreciate it!

  52. You have made some good points there. I looked on the internet
    to learn more about the issue and found most individuals will go along
    with your views on this web site.

Leave a Reply

Your email address will not be published.