loading...
Cover image for Introduction To Asynchronous JavaScript

Introduction To Asynchronous JavaScript

mihinduranasinghe profile image Mihindu Ranasinghe | CyberCats ・2 min read

Introduction

In JavaScript , we need to deal with Asynchronous behaviors.

  • Synchronous Code - In synchronous programs, if you have two lines of code (code1 followed by code2), then code2 cannot begin running until code1 has finished executing.

  • Asynchronous Code- In asynchronous programs, you can have two lines of code (code1 followed by code2), where code1 schedules some task to be run in the future, but code2 runs before that task completes.

Note: JavaScript can have asynchronous code, but it is generally single-threaded.

loadPastAsync(function(){
   //..wait till posts are fetched
   //..Do something with posts
});

doSomeThing(); 
   //Doesn't have to wait until post load

Most Async codes you work with, will be a part of API or a Library

For example,

  • XMLHttpRequest & Fetch
  • jQuery Ajax, Axios, other HTTP Libraries
  • Node.js fs(File System) module

There are a few ways to work with Async Codes

  • Callbacks
  • Promises
  • Async/Await

👏What is AJaX??

AJaX - Asynchronous JavaScript with XML

  • It is a set of web technologies
  • Send & Receive data asynchronously
  • Doesn't interface with the current page
  • JSON has replaced XML for the most parts nowadays.

Request Response Criteria

Importance

  • Make Async requests in the background.
  • No page reload / refresh required(fast).
  • Fetch data.
  • Very interactive.

XmlHttpRequest(XHR) Object

  • API in the form of an object.
  • Provided by the browser JS environment.
  • Methods transfer data between client & server.
  • Can be used with other protocols than Http.
  • Can work with data other than XML(JSON,Plaintext).

What is JSON ??

  • JavaScript Object Notation

Other libraries & methods to make Http requests

  • FetchAPI (Good to work with)
  • Axios (External library)
  • Superagent (External library)
  • jQuery (Not recommend nowadays)
  • Node Http (This is nice if you are using node.js)

👉What's Next?

IF YOU HAVE DONE READING "Introduction To Asynchronous JavaScript" ARTICLE, I SUGGEST YOU TO READ MY NEXT ARTICLE.

Thank You

Hope you all enjoyed and learned something on this. Please let me know your comments suggestions and any questions you have about this blog.

Discussion

markdown guide