Asynchronous - Javascript

  • Callback Functions
    • A function passed into another function as an argument, which is then invoked inside the outer function to complete an action
    • Problems
      • Inversion of Control
        • Giving more control then required
      • Pyramid of Doom
        • Callback inside Callback, gets difficult to manage
  • Promise
    • It is a promise of code execution which either executes or fails, In both cases, will be notified
    • Syntax
          let variable = new Promise(function(resolve, reject) {
              // Successful
              resolve(value);
              // Fails
              reject(value);
          });
      
    • Promise object returned has
      • State
        • Initially "pending", then changes to "rejected" or "fulfilled"
      • Result
        • Initially "undefined", then changes to value of resolved or error when rejected
    • Then
          variable.then(function(result) {
              // Statement
          }, function(error) {
              // Statement
          });
      
    • Catch
          variable.catch(function(error) {
              // Statement
          });
      
    • Finally
          variable.finally(function() {
              // Statement
          });
      
    • Promise Chaining
      • Returning a value will be treated as a resolved promise
    • Multiple Handlers to a Promise
  • Promise API
    • Promise.all([variable1, variable2, variable3])
      • Waits for all promises to resolve and returns an array of their results
      • If any one fails then all others are ignored and it becomes an error
    • Promise.allSettled([variable1, variable2, variable3])
      • Waits for all promise to settle and returns their results as an array of objects with status and value/reason
    • Promise.race([variable1, variable2, variable3])
      • Waits for the first promise to settle and returns its result
    • Promise.any([variable1, variable2, variable3])
      • Waits for the first promise to fullfil and returns its result
      • Throws Aggregate Error if all the promises are rejected
    • Promise.resolve(value)
      • Makes a resolved promise with the given value
    • Promise.reject(error)
      • Makes a rejected promise with the given error
  • Async/Await
    • Theory
      • Async function is asynchronous and always returns a promise
      • Await pauses the async function until the promise returns a result
      • functionName runs when function is resolved and returned a value
    • Syntax
          const functionName1 = async () => {
              // Returns a Promise
          }
          async function functionName2 () {
              let variable = await functionName1();
          }
      
  • Fetch API
    • AJAX => JS can be used to send and return information from network when needed
          // Without options, a get request is sent
          let p = fetch(URL, options);
          p.then((response) => {
              // Object contains "status", "ok", "headers" properties
              () => return response.json();
          }).then((response) => {
              // Object contains "text", "json", "blob", "formData", "arrayBuffer" properties
              console.log(response);
          }).catch((error) => {
              console.log(error);
          })
      
    • POST Request
          const functionName = async () => {
              let response = await fetch(URL, {
                  method: "POST",
                  headers: {
                      "Content-Type": "application/json"
                  },
                  body: JSON.stringify({}),
              });
              let result = await response.json();
              console.log(result);
          }
      
  • Ajax
    • var = new XMLHttpRequest() => Initiate an xhr Object
    • var.open("GET", "url", "boolean") => Make a get request, from where method is making request, if uou want async request or not
    • var.onprogress = function() {statement} => Statements executes on progress
    • Statements executes after load, this.status checks status of the received message based on http status code, this.responseText gives the received output
          var.onload = function () {
              if(this.status === statusCode) {
                  console.log(this.responseText)
              }
          }
      
    • var.send() => Send get request
    • Request has been received and the process is continuing, Action was successfully received, understood, and accepted, Further action must be taken in order to complete the request, Request contains incorrect syntax or cannot be fulfilled, Server failed to fulfill an apparently valid request
      var.onreadystatechange = function () {
          console.log(var.readyState);
      }
      
    • var.open("POST", "url", "boolean")
    • var.getResponseHeader('Content-type', 'type') => Returns the string containing the text of a particular header's value
    • var.send(parameters) => Send post request
Share: