Giter Club home page Giter Club logo

asynchronous-javascript's Introduction

  • in most basic from JavaScript is Synchronous , single threaded and blocking

  • Synchronous means that the code is executed line by line

function one() {
  console.log("one");
}
function two() {
  console.log("two");
}
one();
two();
// logs one then two
  • blocking : no matter how long previous takes to execute , the next task will not be executed until the previous task is done

  • single threaded : means that only one task can be executed at a time. each thread do one task at a time.only one thread main thread that executes the code.

  • Async Js How?

    • just js is not enough.
    • we need new pieces are outside js to help us
    • where browser or node or any js runtime comes into play
    • in web browser web apis help us to make js async
      • setTimeout,setInterval
      • addEventListener
      • callback
      • promise
      • async and await is help us to do this async work

setTimeout()

  • after a set time period is elapsed run block of code
setTimeout(function,durations(in ms),param1,param2)
  • to clear the timeout
const timerId = setTimeout(function,duration,params...)
clearTimeout(timerId)

setInterval()

  • this function repeatedly runs same code over and over again at regular intervale
setInterval(function,durations(in ms),param1,param2)
  • to clear the interval
const timerId = setInterval(function,duration,params...)
clearInterval(timerId)

Some point to notes about timeout and interval

  • timers and interval are not feature of js. implemented by browser or js run time(node,deno,bun etc..)

  • duration parameter is min delay not guaranteed delay

setTimeout(() => {
  console.log("Hello world");
}, 0);

for (let index = 0; index < 10000; index++) {
  console.log(index);
}
  • this code will print 0 to 9999 (it will take some time then) then hello world because 0 is min delay not guaranteed delay

  • it is possible to achieve same effect as setInterval using recursive setTimeout()

setTimeout(function run() {
  console.log("Hello");
  setTimeout(run, 100);
}, 100);

Callback:

  • in javascript function is first class citizen
  • just like any other object we can pass function as argument to another function
  • a function can also return another function
function greet(name) {
  console.log(`Hello ${name}`);
}

function greetJay(greetFn) {
  const name = "Jay";
  greetFn(name);
}

greetJay(greet);
  • any function that is passed as argument to another function is called callback function

  • the function that are accepting callback function are called higher order function

  • callback can be synchronous or asynchronous

  • example of synchronous callback are

let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

nums.sort((a, b) => a - b);
nums.map((num) => num * 2);
  • example of asynchronous callback are
function greet(name) {
  console.log(`Hello ${name}`);
}
setTimeout(greet, 1000, "Jay");
  • problem with callback : callback hell
setTimeout(() => {
  console.log("Hello");
  setTimeout(() => {
    console.log("world");
    setTimeout(() => {
      console.log("Jay");
    }, 1000);
  }, 1000);
}, 1000);

Promise

  • A promise is simply an object that represents the eventual completion or failure of an asynchronous operation

  • A promise always in one of three states

    • pending : initial state , neither fulfilled nor rejected

    • fulfilled : meaning that the operation was completed successfully

    • rejected : meaning that the operation failed

  • promise help us to deal with async code in more readable and manageable way compare to callback

  • callback hell can be avoided by using promise

  • How to create promise

const promise = new Promise();
  • how to fullfil or reject promise
const promise = new Promise((resolve, reject) => {
  if (true) {
    resolve("success");
  } else {
    reject("failure");
  }
});
  • how to execute callback when promise is fulfilled or rejected
promise
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log(err);
  });
  • it is also possible to chain multiple then
promise
  .then((data) => {
    console.log(data);
    return "hello";
  })
  .then((data) => {
    console.log(data);
    return "world";
  })
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log(err);
  });

Async and Await

  • async:

    • the async keyword is used to define an asynchronous function
    • async function is function that is instance of the AsyncFunction constructor
    • unlike normal function async function always return a promise
    async function greet() {
      return "hello";
    }
  • await:

    • the await keyword is used to wait for a promise
    • it can only be used inside async function
    • await keyword can be used to wait for promise to be resolved or rejected
    async function greet() {
      const promise = new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("hello");
        }, 1000);
      });
      const res = await promise;
      console.log(res);
    }

Event loop

Js Event loop video 1

Js Event loop video 2

Js Event loop video 3

js visualizer

asynchronous-javascript's People

Contributors

jay-bhogayata avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.