How to use Async Await in JavaScript.

How to use Async Await in JavaScript.

JavaScript is a bit like The Faceless Men of the programming world.

It can be Asynchronous. It can be Functional. It can be Object-oriented. It can be Client-side. It can be Server-side. The list goes on.

This article will focus on Asynchronous JavaScript.

But wait, JavaScript is a synchronous language!

This means only one operation can be carried out at a time. But that’s not the entire picture here. There are many ways JavaScript provides us with the ability to make it behave like an asynchronous language. One of them is with the Async-Await clause.

What is async-await?

Async and Await are extensions of promises. If you are not clear with the concepts of Promise, you can refer my previous post How to write Promises in JavaScript.

Async

Async functions enable us to write promise based code as if it were synchronous, but without blocking the execution thread. It operates asynchronously via the event-loop. Async functions will always return a value. Using async simply implies that a promise will be returned, and if a promise is not returned, JavaScript automatically wraps it in a resolved promise with its value.

async function firstAsync() {
  return 27;
}

firstAsync().then(alert); // 27

Running the above code gives the alert output as 27, it means that a promise was returned, otherwise the .then() method simply would not be possible.

Await

The await operator is used to wait for a Promise. It can be used inside an Async block only. The keyword Await makes JavaScript wait until the promise returns a result. It has to be noted that it only makes the async function block wait and not the whole program execution.

The code block below shows the use of Async Await together.

async function firstAsync() {
    let promise = new Promise((res, rej) => {
        setTimeout(() => res("Now it's done!"), 1000)
    });

    // wait until the promise returns us a value
    let result = await promise; 
  
    // "Now it's done!"
    alert(result); 
    }
};firstAsync();

Things to remember when using Async Await

We can’t use the await keyword inside of regular functions.

function firstAsync() {
  let promise = Promise.resolve(10);
  let result = await promise; // Syntax error
}

To make the above function work properly, we need to add async before the function firstAsync();

Async Await makes execution sequential

Not necessarily a bad thing, but having paralleled execution is much much faster.

For example:

async function sequence() {
  await promise1(50); // Wait 50ms…
  await promise2(50); // …then wait another 50ms.
  return "done!";
}

The above takes 100ms to complete, not a huge amount of time but still slow.

This is because it is happening in sequence. Two promises are returned, both of which takes 50ms to complete. The second promise executes only after the first promise is resolved. This is not a good practice, as large requests can be very time consuming. We have to make the execution parallel.

That can be achieved by using Promise.all() .

According to MDN:

The Promise.all() method returns a single Promise that resolves when all of the promises passed as an iterable have resolved or when the iterable contains no promises. It rejects with the reason of the first promise that rejects.

Promise.all()

async function sequence() {
    await Promise.all([promise1(), promise2()]);  
    return "done!";
}

The promise.all() function resolves when all the promises inside the iterable have been resolved and then returns the result.

Another method:

async function parallel() {    // Start a 500ms timer asynchronously…
    const wait1 = promise1(50);     // …meaning this timer happens in parallel.
    const wait2 = promise2(50); 
  
    // Wait 50ms for the first timer…
    await wait1; 
    
    // …by which time this timer has already finished.
    await wait2; 
  
    return "done!";}

Async Await is very powerful but they come with caveats. But if we use them properly, they help to make our code very readable and efficient.

I hope you have learned something new! If you found this article useful, be sure to share, clap, follow and support!

Credit @Medium

How to write Promises in JavaScript

How to write Promises in JavaScript

Almost anyone who has used JavaScript, had a love/hate relationship with it at some point. JavaScript is like that girlfriend who is frustrating at times but has something about her which keeps us intrigued. JavaScript has a galore of interesting topics and concepts to explore. Let’s start with one of them- Promises.

JavaScript is a synchronous programming language, but because of callback functions we can make it work like an Asynchronous Programming language.

Promises

Promises in javascript are very similar to promises made in real life.

Definition of promise -Google
  1. After a promise is made, we get an assurance about ‘something’ and we can plan accordingly.
  2. They can be kept or broken.
  3. We can’t act on them immediately. Only after the promise is kept.

According to MDN:

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

Playing with promises has 2 parts-

  1. Creation of Promises
  2. Handling of Promises

Creation

Promises have the basic blueprint

new Promise( /* executor */ function(resolve, reject) { ... } );
                                                               --MDN

The executing function(executor) accepts two parameters resolve and reject which in turn are callback functions. Promises are used for handling asynchronous operations also called blocking code, examples of which are DB, I/O or API calls, which are carried out by the executor function. Once that completes it either calls resolve on success or reject function on error.

Simple example

let promise = new Promise(function(resolve, reject) {if(promise_kept)
  resolve("done");else
  reject(new Error("…"));
  
});

As it can be seen, Promises don’t return values immediately. It waits for the success or failure and then returns accordingly. This lets asynchronous methods return values like synchronous ones. Instead of returning values right away, async methods supply a promise to return the value.

The above paragraph makes one thing clear, It has states!

A promise can be one of these states-

  1. pending — This is the initial state or state during execution of promise. Neither fulfilled nor rejected.
  2. fulfilled — Promise was successful.
  3. rejected — Promise failed.

The states are quite self-explanatory so won’t go in detail. Here is a screenshot for reference.

Handling and Consuming the Promise

In the last section we saw how Promises are created, now let’s see how the promise can be consumed.

const isDone = new Promise()
//...

const checkIfDone = () => {
  isDone
    .then(ok => {
      console.log(ok)
    })
    .catch(err => {
      console.error(error)
    })
}

Running .checkIfDone() will execute the isDone() promise and will wait for it to resolve, using the then callback. If there is an error it will be handled in the catch block.

Chaining Promises

A promise can be returned to another promise , creating a chain of promises. If one fails all others too. Chaining is very powerful combined with Promise as it gives us the control of the order of events in our code.

new Promise(function(resolve, reject) {

  setTimeout(() => resolve(1), 1000); 

}).then(function(result) { 

  alert(result); 
  return result * 3;

}).then(function(result) { 

  alert(result); 
  return result * 4;

}).then(function(result) {

  alert(result); 
  return result * 6;

});

All of the operations return there results to the next then() function on resolve and this process continues till the chain is complete. The last element in the chain return the final result.

Conclusion

This was just a basic gist of JavaScript promises. Promises can do a lot more if used in the right way and the right place.

Credit @Medium

Node.js, MySQL and async/await

Node.js, MySQL and async/await

Writing asynchronous applications in Node.js can be hard to learn, but except for some really simple cases, it cannot be avoided. Accessing a database is an example of an operation which is asynchronous by nature. It means that you have to wait for the results of a query, but while waiting, your program will continue to execute. For example, it can do some calculations or send another query to the database in parallel.

In a traditional, synchronous programming language like PHP, you could simply write:

$result = $connection->query( 'SELECT * FROM users WHERE id = 1' );

In JavaScript, you have three options to write asynchronous code:

1. Using callbacks:

db.query( 'SELECT * FROM users WHERE id = 1', ( err, rows ) => {
  // ... use the result ...
} );

2. Using promises:

db.query( 'SELECT * FROM users WHERE id = 1' ).then( rows => {
  // ... use the result ...
} );

3. Using the await keyword:

const rows = await db.query( 'SELECT * FROM users WHERE id = 1' );

At first, the difference seems purely cosmetic. It’s just different syntax for achieving the same thing. The differences become more obvious when you try to do something more complex.

Limitations of callbacks and promises

In my earlier article, Node.js, MySQL and promises, I gave an example of executing a few queries, one after another, and subsequently closing the connection.

When using plain callbacks, this requires nesting the callback functions and checking the error result in each function, which leads to a “callback hell”.

With promises, the code becomes more elegant, because you can chain multiple then() handlers and use one catch() handler for all errors. However, extracting the query results and closing the connection regardless of a success or error still requires some effort.

The situation becomes even worse when you have to introduce loops and conditions into an asynchronous code. Imagine the following hypothetical synchronous pseudocode:

const users = db.query( 'SELECT * FROM users WHERE id = 1' );
for ( const i in users ) {
  users[ i ].groups = db.query( '...' );
  if ( users[ i ].is_admin )
    users[ i ].modules = db.query( '...' );
}

Implementing this code asynchronously with callbacks would be hard and would make the code almost unreadable. Unfortunately, promises don’t make this much easier:

db.query( ‘SELECT * FROM users WHERE id = 1' ).then( users => {
  let loop = Promise.resolve();
  for ( const i in users ) {
    loop = loop.then( () => db.query( '...' )
      .then( groups => users[ i ].groups = groups ) );
    if ( users[ i ].is_admin ) {
      loop = loop.then( () => db.query( '...' )
        .then( members => users[ i ].members = members ) );
    }
  }
  return loop.then( () => users );
} );

The above code would probably work as intended, but it’s not very readable. When asynchronous operations are dynamically chained like this, it’s hard to determine the order in which they will be executed.

The async/await way

Here’s the same code implemented using the await keyword:

const users = await db.query( 'SELECT * FROM users WHERE id = 1' );
for ( const i in users ) {
  users[ i ].groups = await db.query( '...' );
  if ( users[ i ].is_admin )
    users[ i ].modules = await db.query( '...' );
}

As you can see, it’s almost identical to the synchronous example. It uses traditional programming constructs, such as loop and conditionals, and the execution order becomes obvious. That’s why it’s very easy to read and write such code.

Error handling is also more explicit, because you can use constructs like try/catch and try/finally. This makes it easier to see which error handler is associated with a particular block of code.

When you are just beginning to use it, the async/await syntax seems like some dark magic. It’s important to understand that it’s actually just syntactic sugar for regular promises which are used behind the scenes. This means that you can freely mix promises with async/await.

An async function is simply nothing more than a function that is guaranteed to return a promise. You can use it like any other function which returns a promise:

async function foo() {
  return 42;
}foo().then( result => console.log( result ) );

This code will print 42.

On the other hand, within an async function, you can use the await keyword with any promise, not only to call other async functions:

const foo = Promise.resolve( 42 );console.log( await foo );

This will print 42 as well.

This is very important, because we can wrap any existing function which uses callbacks to return a promise, and call that function using the async/await syntax.

Using async/await with MySQL

Let’s create a simple promise based database wrapper using the mysql module for Node.js:

const util = require( 'util' );
const mysql = require( 'mysql' );function makeDb( config ) {
  const connection = mysql.createConnection( config );  return {
    query( sql, args ) {
      return util.promisify( connection.query )
        .call( connection, sql, args );
    },
    close() {
      return util.promisify( connection.end ).call( connection );
    }
  };
}

It’s similar to the Database class I implemented in the previous article, only this time it’s a factory function instead of a class, and it uses the promisify() utility function to keep things simple. But it works the same, so both the query() and close() functions return a promise.

The example code from the previous article can be rewritten using async/await:

const db = makeDb( config );
try {
  const someRows = await db.query( 'SELECT * FROM some_table' );
  const otherRows = await db.query( 'SELECT * FROM other_table' );
  // do something with someRows and otherRows
} catch ( err ) {
  // handle the error
} finally {
  await db.close();
}

We can add support for transactions by promisifying the beginTransaction()commit() and rollback() functions in our database wrapper:

return {
  ...,
  beginTransaction() {
    return util.promisify( connection.beginTransaction )
      .call( connection );
  },
  commit() {
    return util.promisify( connection.commit )
      .call( connection );
  },
  rollback() {
    return util.promisify( connection.rollback )
      .call( connection );
  }
};

The above code rewritten to use transactions looks like this:

const db = makeDb( config );
try {
  await db.beginTransaction();
  const someRows = await db.query( 'SELECT * FROM some_table' );
  const otherRows = await db.query( 'SELECT * FROM other_table' );
  // do something with someRows and otherRows
  await db.commit();
} catch ( err ) {
  await db.rollback();
  // handle the error
} finally {
  await db.close();
}

To avoid repeating this boilerplate code every time, we can create a helper function which executes arbitrary asynchronous code within a transaction:

async function withTransaction( db, callback ) {
  try {
    await db.beginTransaction();
    await callback();
    await db.commit();
  } catch ( err ) {
    await db.rollback();
    throw err;
  } finally {
    await db.close();
  }
}

As you can see, the callback parameter is expected to be a function returning a promise.

With this helper function, the above code can be simplified to this:

const db = makeDb( config );
try {
  await withTransaction( db, async () => {
    const someRows = await db.query( 'SELECT * FROM some_table' );
    const otherRows = await db.query( 'SELECT * FROM other_table' );
    // do something with someRows and otherRows
  } );
} catch ( err ) {
  // handle error
}

Here we use the async keyword with an arrow function to easily create an asynchronous callback function.

Final notes

From my experience, once you get used to writing code using async/await, it’s hard to imagine how you could live without it. However, to be able to write asynchronous code, you still need to understand promises, and in order to use promises, you need to understand callbacks.

Note that the async/await syntax only works in Node.js version 8 or newer, so if you are still using an older version, you should consider updating it.

You can also use async/await in client side code if you are targetting modern browsers. If you have to support IE, it’s also possible with the help of transpilers and polyfills, but that’s outside of the scope of this article.

@Credit CodeBurst.io

Understanding Asynchronous JavaScript – Learn How JavaScript Works

Understanding Asynchronous JavaScript – Learn How JavaScript Works

JavaScript is a single-threaded programming language which means only one thing can happen at a time. That is, the JavaScript engine can only process one statement at a time in a single thread.

While the single-threaded languages simplify writing code because you don’t have to worry about the concurrency issues, this also means you can’t perform long operations such as network access without blocking the main thread.

Imagine requesting some data from an API. Depending upon the situation the server might take some time to process the request while blocking the main thread making the web page unresponsive.

That’s where asynchronous JavaScript comes into play. Using asynchronous JavaScript (such as callbacks, promises, and async/await), you can perform long network requests without blocking the main thread.

While it’s not necessary that you learn all these concepts to be an awesome JavaScript developer, it’s helpful to know 🙂

So without further ado, Let’s get started 🙂

Tip: Using Bit you can turn any JS code into an API you can share, use and sync across projects and apps to build faster and reuse more code. Give it a try.


How Does Synchronous JavaScript Work?

Before we dive into asynchronous JavaScript, let’s first understand how the synchronous JavaScript code executes inside the JavaScript engine. For example:

const second = () => {
  console.log('Hello there!');
}const first = () => {
  console.log('Hi there!');
  second();
  console.log('The End');
}first();

 

To understand how the above code executes inside the JavaScript engine, we have to understand the concept of the execution context and the call stack (also known as execution stack).

Execution Context

An Execution Context is an abstract concept of an environment where the JavaScript code is evaluated and executed. Whenever any code is run in JavaScript, it’s run inside an execution context.

The function code executes inside the function execution context, and the global code executes inside the global execution context. Each function has its own execution context.

Call Stack

The call stack as its name implies is a stack with a LIFO (Last in, First out) structure, which is used to store all the execution context created during the code execution.

JavaScript has a single call stack because it’s a single-threaded programming language. The call stack has a LIFO structure which means that the items can be added or removed from the top of the stack only.

Let’s get back to the above code snippet and try to understand how the code executes inside the JavaScript engine.

const second = () => {
  console.log('Hello there!');
}const first = () => {
  console.log('Hi there!');
  second();
  console.log('The End');
}first();

 

Call Stack for the above code

So What’s Happening Here?

When this code is executed, a global execution context is created (represented by main()) and pushed to the top of the call stack. When a call to first() is encountered, it’s pushed to the top of the stack.

Next, console.log('Hi there!') is pushed to the top of the stack, when it finishes, it’s popped off from the stack. After it, we call second(), so the second() function is pushed to the top of the stack.

console.log('Hello there!') is pushed to the top of the stack and popped off the stack when it finishes. The second() function finishes, so it’s popped off the stack.

console.log(‘The End’) is pushed to the top of the stack and removed when it finishes. After it, the first() function completes, so it’s removed from the stack.

The program completes its execution at this point, so the global execution context(main()) is popped off from the stack.

How Does Asynchronous JavaScript Work?

Now that we have a basic idea about the call stack, and how the synchronous JavaScript works, let’s get back to the asynchronous JavaScript.

What is Blocking?

Let’s suppose we are doing an image processing or a network request in a synchronous way. For example:

const processImage = (image) => {
  /**
  * doing some operations on image
  **/
  console.log('Image processed');
}const networkRequest = (url) => {
  /**
  * requesting network resource
  **/
  return someData;
}const greeting = () => {
  console.log('Hello World');
}processImage(logo.jpg);
networkRequest('www.somerandomurl.com');
greeting();

 

Doing image processing and network request takes time. So when processImage() function is called, it’s going to take some time depending on the size of the image.

When the processImage() function completes, it’s removed from the stack. After that the networkRequest() function is called and pushed to the stack. Again it’s also going to take some time to finish execution.

At last when the networkRequest() function completes, greeting() function is called and since it contains only a console.log statement and console.log statements are generally fast, so the greeting() function is immediately executed and returned.

So you see, we have to wait until the function (such as processImage() or networkRequest()) has finished. This means these functions are blocking the call stack or main thread. So we can’t perform any other operation while the above code is executing which is not ideal.

So what’s the solution?

The simplest solution is asynchronous callbacks. We use asynchronous callbacks to make our code non-blocking. For example:

const networkRequest = () => {
  setTimeout(() => {
    console.log('Async Code');
  }, 2000);
};console.log('Hello World');networkRequest();

 

Here I have used setTimeout method to simulate the network request. Please keep in mind that the setTimeout is not a part of the JavaScript engine, it’s a part of something known as web APIs (in browsers) and C/C++ APIs (in node.js).

To understand how this code is executed we have to understand a few more concepts such event loop and the callback queue (also known as task queue or the message queue).

An Overview of JavaScript Runtime Environment

The event loop, the web APIs and the message queue/task queue are not part of the JavaScript engine, it’s a part of browser’s JavaScript runtime environment or Nodejs JavaScript runtime environment (in case of Nodejs). In Nodejs, the web APIs are replaced by the C/C++ APIs.

Now let’s get back to the above code and see how it’s executed in an asynchronous way.

const networkRequest = () => {
  setTimeout(() => {
    console.log('Async Code');
  }, 2000);
};console.log('Hello World');networkRequest();console.log('The End');

 

Event Loop

When the above code loads in the browser, the console.log(‘Hello World’) is pushed to the stack and popped off the stack after it’s finished. Next, a call to networkRequest() is encountered, so it’s pushed to the top of the stack.

Next setTimeout() function is called, so it’s pushed to the top of the stack. The setTimeout() has two arguments: 1) callback and 2) time in milliseconds (ms).

The setTimeout() method starts a timer of 2s in the web APIs environment. At this point, the setTimeout() has finished and it’s popped off from the stack. After it, console.log('The End') is pushed to the stack, executed and removed from the stack after its completion.

Meanwhile, the timer has expired, now the callback is pushed to the message queue. But the callback is not immediately executed, and that’s where the event loop kicks in.

The Event Loop

The job of the Event loop is to look into the call stack and determine if the call stack is empty or not. If the call stack is empty, it looks into the message queue to see if there’s any pending callback waiting to be executed.

In this case, the message queue contains one callback, and the call stack is empty at this point. So the Event loop pushes the callback to the top of the stack.

After that the console.log(‘Async Code’) is pushed to the top of the stack, executed and popped off from the stack. At this point, the callback has finished so it’s removed from the stack and the program finally finishes.

DOM Events

The Message queue also contains the callbacks from the DOM events such as click events and keyboard events. For example:

document.querySelector('.btn').addEventListener('click',(event) => {
  console.log('Button Clicked');
});

 

In case of DOM events, the event listener sits in the web APIs environment waiting for a certain event (click event in this case) to happen, and when that event happens, then the callback function is placed in the message queue waiting to be executed.

Again the event loop checks if the call stack is empty and pushes the event callback to the stack if it’s empty and the callback is executed.

We have learned how the asynchronous callbacks and DOM events are executed which uses the message queue to store all the callbacks waiting to be executed.

ES6 Job Queue/ Micro-Task queue

ES6 introduced the concept of job queue/micro-task queue which is used by Promises in JavaScript. The difference between the message queue and the job queue is that the job queue has a higher priority than the message queue, which means that promise jobs inside the job queue/ micro-task queue will be executed before the callbacks inside the message queue.

For example:

console.log('Script start');setTimeout(() => {
  console.log('setTimeout');
}, 0);new Promise((resolve, reject) => {
    resolve('Promise resolved');
  }).then(res => console.log(res))
    .catch(err => console.log(err));console.log('Script End');

Output:

Script start
Script End
Promise resolved
setTimeout

 

We can see that the promise is executed before the setTimeout, because promise response are stored inside the micro-task queue which has a higher priority than the message queue.

Let’s take another example, this time with two promises and two setTimeout. For example:

console.log('Script start');setTimeout(() => {
  console.log('setTimeout 1');
}, 0);setTimeout(() => {
  console.log('setTimeout 2');
}, 0);new Promise((resolve, reject) => {
    resolve('Promise 1 resolved');
  }).then(res => console.log(res))
    .catch(err => console.log(err));new Promise((resolve, reject) => {
    resolve('Promise 2 resolved');
  }).then(res => console.log(res))
    .catch(err => console.log(err));console.log('Script End');

This prints:

Script start
Script End
Promise 1 resolved
Promise 2 resolved
setTimeout 1
setTimeout 2

We can see that the two promises are executed before the callbacks in the setTimeout because the event loop prioritizes the tasks in micro-task queue over the tasks in message queue/task queue.

While the event loop is executing the tasks in the micro-task queue and in that time if another promise is resolved, it will be added to the end of the same micro-task queue, and it will be executed before the callbacks inside the message queue no matter for how much time the callback is waiting to be executed.

For example:

console.log('Script start');setTimeout(() => {
  console.log('setTimeout');
}, 0);new Promise((resolve, reject) => {
    resolve('Promise 1 resolved');
  }).then(res => console.log(res));new Promise((resolve, reject) => {
  resolve('Promise 2 resolved');
  }).then(res => {
       console.log(res);
       return new Promise((resolve, reject) => {
         resolve('Promise 3 resolved');
       })
     }).then(res => console.log(res));console.log('Script End');

This prints:

Script start
Script End
Promise 1 resolved
Promise 2 resolved
Promise 3 resolved
setTimeout

So all the tasks in micro-task queue will be executed before the tasks in message queue. That is, the event loop will first empty the micro-task queue before executing any callback in the message queue.

Conclusion

So we have learned how asynchronous JavaScript works and other concepts such as call stack, event loop, message queue/task queue and job queue/micro-task queue which together make the JavaScript runtime environment. While it’s not necessary that you learn all these concepts to be an awesome JavaScript developer, but it’s helpful to know these concepts 🙂

Credit @medium