Make JavaScript code Asynchronous

JavaScript is a "single-threaded" language because it has a single execution thread in the browser environment. This means that JavaScript code is processed in a sequential, single-threaded manner by default.

let's look into the code

let a = 10;
for (let i = 0; i < 1000000000; i++ {
// doing something...
}
console.log(a)

if we run above code it will take a long running time to get executed and then after we will able to see the value a.

this is clearly making our code slow and degrading the performance if we work on real life projects.

To make our even better and fast asynchronous concept is came into JavaScript programming.

let a = 10
setTimeout(() => {
  for (let i = 0; i< 1000000000; i++) {
    // doing something...
  }
}, 0);
console.log(a);

but if we write in this manner variable a won't have to wait for loop to be get executed.

this is what a asynchronous is. JavaScript does not wait for anything it quickly executes a program, if something taking too much time then JavaScript send it to callback queues and then fetch that code one it get done.

Using Promises

with the introduction of Promises JavaScript developers gained more readable ways to handle asynchronous tasks. promises can be handle via two ways

  • then and catch methods

  • async await

let's check then and catch method

function getData() {
  let p = new Promise((resolve, reject) => {
    let connection = true
    if (connection) {
      resolve ({name: "john doe"})
    }else {
      reject ("connection failure")
    }
  })
  console.log("hello");
  return p
}
getData().then((result) => {
  console.log(result);
}).catch((err) => {
  console.log(err);
});
getData.signal = "OK"
console.log(getData.signal);

// Output
// hello
// OK
// { name: 'john doe' }

as we can see the output, although the result is consoled first but getData.signal is printed because promise is taking a little bit longer time so it get stored in callback queue and when the task is get completed it then get back call stack to get execute.

Using async await

async/await syntax, makes the asynchronous tasks even more easy to understand.

function fetchData() {
  let p = new Promise((resolve, reject) => {
    let connection = true
    if (connection) {
      resolve ({name: "john doe"})
    }else {
      reject ("connection failure")
    }
  })
  console.log("hello");
  return p
}

async function getResult () {
  let res = await fetchData()
  console.log(res);
}
getResult()
getResult.signal = "OK"
console.log(getResult.signal);

// output
// hello
// OK
// { name: 'john doe' }

Above code is reformed version of then catch method where we just creating a new function getResult and invoking it.