JavaScript: Async functions (async/await)

JavaScript: Async functions (async/await)


I am sure that many of you are using async and await already. But, I think it deserves a little more attention. 

 Every one should remember Mozilla docs is your friend.

Here is the MDN definition for async and await:

async:

“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.” 

 await: 

“An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value. Remember, the await keyword is only valid inside async functions.” 

 Confused……….. 

 Lets put this defination in this way 

 A function defined as async is a function that can perform asynchronous actions but still look synchronous. The way it's done is using the await keyword to defer the function while it waits for a Promise to resolve or reject. 

 async and await build on top of promises and generators to express asynchronous actions inline. This makes asynchronous or callback code much easier to maintain. 


Syntax:

async function name([param[, param[, ...param]]]) {
   statements
}

 Let see its implementation: 

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: "resolved"
}

asyncCall();



OUTPUT:> "calling"
        > "resolved"

 An async function always returns a Promise itself, so you can use it in other asynchronous functions.


SomeThing you should know about Await:

Await and operator precedence:

You have to keep the operator precedence in mind when using await keyword.

Imagine that we have an asynchronous function which calls another asynchronous function, getData() which returns a Promise that resolves to an instance of class Data. Now we want to get the size of the Data using the getDataSize() method of that class.

Look at the following code:

                    async function myAsyncFunction() 
                        {

                   await getData().getDataSize();
              }


By looking this it we think code is fine but if we take precedence in the picture it looks like:

                 async function myAsyncFunction() 
                        {
                            await (getData().getDataSize());
                         }

Here we attempt to call getDataSize() method of the Promise object, which isn't what we want.

Instead, we should use brackets to denote that we first want to wait for the getData, and then call getDataSize() method of the result: 

                async function myAsyncFunction() 
                        {
                        (await getData()).getDataSize(); 
                        }

Of course. the previous version could be valid in some cases, for example, if the getData() function was synchronous, but the getDataSize() method was asynchronous.


But we should Take of this prcedence.


These are the basic things about Async Await if you need more info then please comment below.

Note:The content is as per my knowledge and with some reference .If i am wrong please correct me. 

Thanks
Muktha

Reference:goalkicker.com




Comments

  1. That's very useful content share your blog well go on thanks a lot

    ReplyDelete
    Replies
    1. Thanks for your comment. We are looking forward to improve more.

      Delete

Post a Comment

Popular posts from this blog

DATA Structures :Binary Search Trees

Angular 2+ :@view Child

Angular -Lazy Loading

DBMS-Data Models

OOPS Concepts-JAVA