Asynchronous Programming: 10 minutes of your interview covered

What? Why? How? And which one is better? To get you that God-level confidence in your next interview.

ยท

6 min read

Javascript is synchronous by nature. In simple words, the second task will not be started until the first one is completed.

Now,Lets play a game of points. It will determine how much you can score in interviews. LITERALLY!!!! 10 points for you if you can guess the output of the following code snippet:

console.log("I am first");
     function secondTask(){
             console.log("I am second");
          }
      secondTask();
    function thirdTask(){
             console.log("This is called sync.");
          }

For the output, "I am first" will be printed followed by secondTask() and thirdTask().

Was that easy? Did you get 10? or 9?

To understand the backstage work, we need to know that javascript is a single-threaded programming language i.e, it can only perform one task at a time.

So, In the above code console.log gets added to call stack and after printing the output it is removed from the stack. Same way, the next function gets added to the stack, and when it is called, it gets executed and removed from the stack. The same thing is repeated and so on.

Repeat-Blog-Image-2.png

This repeat and wait thing is okay but what if the code is complex, long, and requires a lot of waiting. But the world and Javascript wait for NO ONE. (ooo...that was deep.)

And when someone keeps you waiting, a solution enters your life, like this.๐Ÿ‘‡

post-1.jpg

And here the name of this hero is Async JS. Consider this code to get 10 points more.

console.log("I am first");
     setTimeout(() => {
         console.log('I am first but 3 seconds late');
                               }, 3000); 
console.log("I am async JS.");
//setTimeout is a function provided by JS to perform async operations.

So this program will get the output like "I am first" followed by "I am async JS" and "I am first but 3 seconds late". Now what if setTimeout() is set to 0. Will the output change?

If you answer this, Give yourself 15 points. And if you answer this right, Give yourself 20 points.

So, this is the need for async JS. In short, asynchronous programming is a technique that ensures that your program is able to respond to other events while the tasks run. Once the task is completed, your program presents the output. Even if you don't need to write your own async daily, you may need to learn how to use them, as it saves a lot of time. Many functions provided by the browser, like fetch(), and getUserMedia() take a lot of time, and hence, they are all async.

We will further discuss:

  1. Callbacks
  2. Promises
  3. Async/Await

Callback

One thing good about this, It is less annoying than my friends saying "call you back".

confused.jpg

Anyways let's move on in life and in this article too, Callback (IN JS) is a function passed as an argument to another function, this technique will help a function to call another function. one function will run after the other one.

I told you, this is annoying. LESS. ANNOYING. But heyy.. you can make this intresting!!!

finaleasy.png

its just like your mom asked you(function A ) to clean the dishes and you asked your younger brother(function B) to execute the task.

one function in another function.

EASY PEASY LEMON SQUIZZY!

Now it's time to get real technical, a callback function is a shining star and helps us save a lot of "wait". Like when one function requires waiting for another function(like waiting for an image or a file to load). A quick example of callback function can be this-

function greeting(name) {
  alert('Hello ' + name);
}

function processUserInput(callback) {
  var name = prompt('Please enter your name.');
  callback(name);
}

processUserInput(greeting);

So in this example, we understood the synchronous call back function while async callback is used with fetch() in APIs. But the problem with mordern day usage of asynchronous call back function in API, fails. To handle this kind of errors we again need to use one callback function which may lead to multiple callbacks and ultimately system crash. This is when Promises come to rescue.

The JS world with promises!

The Promise is an object which directs us to the completion or the failure of an async operation and its result value. The value of promise is not necesarily known at the time of creation. The value of promise can in one of the following state,

  1. pending: neither sucess nor failure, initial stage
  2. fulfilled: the operation was completed successfully.
  3. rejected: the operation failed. The following code uses promises:
function successCallback(result) {
  console.log("Audio file ready at URL: " + result);
}

function failureCallback(error) {
  console.error("Error generating audio file: " + error);
}

createAudioFileAsync(audioSettings, successCallback, failureCallback);
//createAudioFileAsync() were rewritten to return a promise

createAudioFileAsync(audioSettings).then(successCallback, failureCallback);

Promises have several advantages unlike old-fashioned passed-in callbacks, a promise comes with guarantees like multiple callbacks can be added by calling then(). it is also helpful when we want to use multiple async operations back to back, by creating a promise chain. Also to pass an error, instead of resolving it, we reject it and when we consume that promise we can use .catch to throw an error message.

To conclude, promises solve the issue of callback hell, and deals with error in a great way. But people with high demands, had problems with .then() so they found a still better way. (okay, not better but different).

Async/Await

It is based on promises but just different. As per mdn docs, An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains. If you dont understand this, think it like this. Async await is a different version of promise. We can use this with a keyword in front of the function declared. SIMPLE!!!!!

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();

If you wish to safely perform two or more jobs in parallel, use await. async functions always return a promise, or they come wrapped in promise. await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. The resolved value of the promise is treated as the return value of the await expression. Use of async and await enables the use of ordinary try / catch blocks around asynchronous code.

Repeat-Blog-Image-2.png

This is a huge concept and important as well. Please count all the points and add 30 points as bonus. You have done a great job. Now, All you have to do is to find the practical implementation in your projects.

Happy learning! Shavi.

ย