ASYNC/AWAIT in JS

A potent pair of keywords in standard JavaScript ES2017.

Photo by Ferenc Almasi on Unsplash

avaScript language is single-thread, i.e., only one thread only to execute the command line. If running under a synchronized (synchronous), then when performing complex calculations, call AJAX request to the server, call the database (in NodeJS), this thread will stop waiting to do the whole browser is… crash.

To avoid this, most code call AJAX request or database in JavaScript are running under the asynchronous. Initially, the running code asynchronous in JavaScript is a reality thanks to the callback (as the code below).

// Pass callback to function ajax
var callback = function(image) {
console.log(image);
};
ajax.get("hotgirl.info", callback);

// Can be abbreviated as follows
ajax.get("hotirl.info", function(image) {
console.log(image);
})

Of course, because the callback has some disadvantages such as verbose code, callback, …, people created a new pattern called Promise!

From callback, promise comes to Async/Await.

Promise solved the callback problems quite well. Code becomes easier to read, separate, and error-prone.

The code becomes neat when moving from callback to promise.

However, using promises is sometimes still a bit annoying because we have to pass the callback to the then and catch function. The code will also be a bit redundant and difficult to debug because all the functions then count as one statement, so it is impossible to debug each line individually.

Fortunately, in ES7, a miracle called async / await was born. (I think 99% that this miracle is stealing from great C # because C # has had async / await since the time he took off school).

See Promise objects as if they were synchronized objects.

So what’s async / await interesting? They help us write code that looks synchonous but actually runs asynchonous.

As shown in the picture above, the findRandomImgPromise function is an asynchronous function that returns a Promise. With the await keyword, we can consider this function synchronous; the following statement can only be run after the function returns.

Why use async / await?

As I said, async / await has several advantages over promises:

  • The code is much easier to read, no need to catch anything; write like code running sequentially, and then use normal try/catch to catch errors.
  • Writing a loop through each element becomes extremely simple, await in each loop.
  • Debug is much easier since each awaits use counts as a single line of code, so you can set the debugger to debug each line as usual.
  • When there is an error, the exception will indicate the error on the line number but not generally resolved to the promise.
  • With promises or callbacks, combining an if / else or a retry with asynchnous code is a pain because we have to write code around, complicated. With async / await, this is extremely easy.
Async / Await makes the code neat.

Shortcomings of async / await

Of course, async / await also has some shortcomings that you need to keep in mind when using:

  • It cannot run on older browsers. If the project requires running on older browsers, you’ll have to use Babel to transpiler the code to ES5 to run.
  • When we await a rejected promise, JavaScript will throw an exception. Therefore, if we use async-await and forget to try-catch, we will get… swallowed errors or code stops running.
  • Async and await must come together! await can only be used in async functions. Otherwise, there will be a syntax error. Hence, async / await will spread over all the functions in your code.

Apply async / await to your code

In essence, an async function will return a promise, corresponding to Task in C #. Therefore, to use async / await effectively, you must understand the working mechanism of Promise!

Currently, the latest versions of Chrome, Edge, and Firefox already support async / await; if the project does not require support for old browsers, feel free to use async / await to make the code neater.

Besides, if you use NodeJS, you can use the Promisify + Async / Await combo as follows:

  1. Use Bluebird or util. promiscuity (Node 8 and up) to turn NodeJS callback functions into Promise.
  2. Use async / await to get results from these Promises.

Always be nice to anybody who has access to my toothbrush.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store