Asynchronous

Asynchronous


Synchronous vs Asynchronous

Waterfall chart showing the difference between sync vs async tasks
Waterfall chart showing the difference between sync vs async tasks
  • Synchronous code means code that executes in a sequence and is blocking, asynchronous code is executed in parallel
  • JavaScript is a synchronous single-threaded language but we can use asynchronous code with the help of our environment and event loop

setTimeout

  • This is an async function provided to us by the browser that takes in 2 arguments, first the callback function to execute and the second is the time duration in milliseconds
  • This executes some code after given duration
  • In the code example below, setTimeout() executes at last even though the time we have provided is 0 milliseconds because the main stack is executed first and only then things from side stack are added
console.log("Hello"); setTimeout(() => console.log("Inside"), 0) console.log("Bye"); // Output "Hello" "Bye" "Inside"

setInterval

  • Similar to setTimeout, setInterval keeps running a function after the given duration
  • We can clear setInterval using clearInterval

Callbacks

And understanding callback hell
TODO: Add description

Promises

  • A promise is a language feature whose value will be available after some given time
  • A promise can have three states: Pending, Fulfilled or Failed

Creating Promise

  • We can create a promise using the Promise constructor
  • This promise randomly either resolves or rejects
  • The value of promise variable will be Pending
const promise = new Promise((resolve, reject) => { // Creating random true or false const randBool = Boolean(Math.floor(Math.random() * 2)); if(randBool){ resolve('Hey response') } else { reject("Sorry something went wrong") } }) console.log(promise); // pending

Consuming Promises

  • We can consume (use) a promise with 2 types of syntax

1. Chaining .then and .catch

  • We can nest .then to a promise. The value of previous .then will be passed on to the next .then and so on. This is called chaining
  • The .catch block runs in case of any error
  • The .finally runs at the end no matter what happens. It’s good for cleanup tasks that we might want to run eventually
promise .then(data => console.log(data)) .catch(error => console.error(error)) .finally(() => console.log("Executed"))

2. Using await inside async

  • This is a cleaner ES6 syntax for the .then chaining
  • It basically does the same thing as .then but in a more cleaner and synchrnous looking code
  • Await will wait for the code to finish executing before moving ahead
  • The await keyword can only be used inside an async function (that’s the catch)
function getData(){ const data = await promise(); }

Fetch API

Things to remember in an API request: things might go wrong and a request always takes some time, it's not instantaneous
  • Fetch API is provided to us by the browser and also node. This is used to get some data from a network request
  • There is also XHR (XMLHttpRequest) that we can use to get some data in the browser but its use is now obselete instead fetch is more modern and better

Using Fetch

notion image
  • We have to pass the URL with fetch, we can also pass additional parameters depending on our request
  • Most common get request can be made using this code block
fetch(URL) .then(res => res.json()) .then(data => data) .catch(err => console.error("Something went wrong", err)) .finally(() => "Request complete")
  • We have to parse our response using res.json() as the response is a readable stream and we need to convert it to JS before using it

init Object

  • Fetch also accepts another optional parameter called init which takes in more information
  • This can be used to make all types of requests such as POST or DELETE and also settings headers
notion image

Axios

  • It is an npm package that provides more cleaner way of making network requests
  • It is cross-environment meaning that we can use it for browser as well as node
  • It is more cleaner as compared to the normal fetch

Interceptor in Axios

  • It allows us to use modify a request or response