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.

The code becomes neat when moving from callback to promise.
See Promise objects as if they were synchronized objects.

Why use async / await?

  • 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

  • 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

  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.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Android X , reactNative hermes migration at redBus — A military style operation

How to Use reduce() in JavaScript

VueJs Form Validation Part 1 — VeeValidate

JavaScript Let vs Var vs Const

JavaScript DOM and how to navigate it with a <form> example, Part 2: Collecting form values

Create styled-components library

Realtime Shopping List App with AWS Amplify, AppSync, GraphQL, and Vue.js

What is Destructuring?

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.

More from Medium

Best Search Packages for JavaScript

Express Middleware Explained in One Minute

JavaScript Error Handling

Uses of JavaScript and MongoDB