ASYNC/AWAIT in JS

Photo by Ferenc Almasi on Unsplash
// 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);
})

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.
See Promise objects as if they were synchronized objects.

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!

  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.

--

--

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
Beribey

Beribey

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