JavaScript Asynchronous

Introduction

JavaScript Asynchronous

Contents

  1. Asynchronous functions
  2. Callback & Promise in JavaScript
  3. ES8 async await

1. Asynchronous functions

JavaScript that is a single-threaded language can be non-blocking with Asynchronous.

A program has to do simple things. It has to allocate memory. It also has to parse and execute function which means read and run commands. Single-threaded means that it has only one call stack. So, it can only do one thing at a time. Call Stack is first in last out. Other languages can have multiple call stacks and these are called multi-threaded. You can also see how that might be beneficial to have multiple call stack. Why was JavaScript designed to be single-threaded? because a multi-threaded environment can have Dead locks. Again, JavaScript is a single-threaded language that can be non-blocking. It has one call stack and it does one thing at a time In order to non-block the single-threaded language,

It should be Asynchronous with call back functions and these callback functions get to run in the background through the callback queue and then the Event Loop to bring it back into the call stack.

2. Callback & Promise in JavaScript

A Promise is a new feature in ES6 JavaScript.

A promise is an object that may produce a single value some time in the future. It will be resolved a value or it will not be resolved (rejected).

A promise in one of three possible state Rejected

  1. Fullfilled
  2. Rejected
  3. Pending

Before promise, JavaScript only have callbacks.

Callbacks are the cornerstone of asynchronous JavaScript programming, and callback is a function passed into another function as an argument to be executed later.

Example of Callback

let foods = ["apple", "blueberry", "Mango"];
foods.forEach(function callback(food){
    console.log(food);
});
apple
blueberry
Mango

Also, Passing a callback as a predefined function

let foods = ["apple", "blueberry", "Mango"];

function a(food){
    console.log(food)
}
foods.forEach(a);
apple
blueberry
Mango
  • function a is used as callback function.

Create our own callback function

function a(callback) {
    callback("callback is working")
}

a(function (data) {
    console.log(data)
});
callback is working

However, callback you can get the nested function which called as “Callback Hell“. So, sometimes you need promise for code readability.

Promise with multiple callback.

let promise = new Promise(function (resolve, reject) {
    setTimeout(function () {
        resolve('Hello World');
    }, 1000);
});

promise.then(function (data) {
    console.log(data)
    return data + " I like you"
}).then(function (data) {
    console.log(data)
}).then(function (data) {
    console.log(data)
}).catch(() => console.log("error!"))
first layer: Hello World
second layer: Hello World I like you
third layer: undefined

After one second “Hello world” is resolved which is used in first layer and first layer return another value which is used second layer with no return, so third layer data is undefined.

You can use a promise with the task happens such as APIs Call. When the promise gets resolved or rejected then you will get the response.

More Promise Example

let promise1 = new Promise((resolve, reject) => {
    setTimeout(function () {
        resolve('Hello');
    }, 50);
})

let promise2 = new Promise((resolve, reject) => {
    setTimeout(function () {
        resolve('World');
    }, 500);
})

let promise3 = new Promise((resolve, reject) => {
    setTimeout(function () {
        resolve('With Promise');
    }, 5000);
})

Promise.all([promise1, promise2, promise3]).then(x => {
    console.log(x)
})
[ 'Hello', 'World', 'With Promise' ]
  • After 5 Second Promise.all resolved.

A Promise can only succeed or fail only once. It can not succeed or fail twice, and this is extremely useful for things that are asynchronous success and failure such as APIs calls. Fetch Simple returns a promise.

3. ES8 async await

Async await is part of ES8 and is built on top of promises.

Async function is a function that returns a promise, but the benefit of async await is that makes code easier to read. A promise in JavaScript is that promise to return something to you in the future. For example, from database or APIs calls. These requests take time.

Default async vs ES8 async await

const fetch = require("node-fetch");

const fetchUserByDefault = function () {
  fetch("https://jsonplaceholder.typicode.com/users")
    .then((res) => res.json())
    .then(function (data) {
      console.log("Default Aysnc way");
      console.log(data[data.length - 1].id);
    });
};

const fetchUsersByAsync = async function () {
  const res = await fetch("https://jsonplaceholder.typicode.com/users");
  const data = await res.json();
  console.log("ES8 Async Function way");
  console.log(data[data.length - 1].id);
};

fetchUserByDefault();
fetchUsersByAsync();
Default Aysnc way
10
ES8 Async Function way
10

Promise.all and try and catch

cconst fetch = require("node-fetch");

const urls = [
  "https://jsonplaceholder.typicode.com/users",
  "https://jsonplaceholder.typicode.com/posts",
];

const allDataFromUrls = async function () {
  try {
    const [users, posts] = await Promise.all(
      urls.map((url) => fetch(url).then((res) => res.json()))
    );
    console.log(users[users.length - 1].id);
    console.log(posts[posts.length - 1].id);
  } catch (err) {
    console.log("error: " + err);
  }
};

allDataFromUrls();
10
100

Leave a Reply

Your email address will not be published.

ANOTE.DEV