Javascript async: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 171: Line 171:
   request.then((result) => setText(result)).catch((reason) => setText(reason));
   request.then((result) => setText(result)).catch((reason) => setText(reason));


</syntaxhighlight>
==Promise All==
This is used to send multiple requests. The Promise.All function will waiting until either '''all''' fulfill or '''one'' rejects. Here is an example using axios.
<syntaxhighlight lang="javascript">
  let itemCategories = axios.get("http://localhost:3000/itemCategories");
  let orderStatuses = axios.get("http://localhost:3000/orderStatuses");
  let userTypes = axios.get("http://localhost:3000/userTypes");
  Promise.all([itemCategories, orderStatuses, userTypes])
    .then(([categories, statuses, types]) => {
      setText("");
      setText(JSON.stringify(categories.data));
      setText(JSON.stringify(statuses.data));
      setText(JSON.stringify(types.data));
    })
    .catch((reasons) => {
      setText(reasons);
    });
</syntaxhighlight>
</syntaxhighlight>

Revision as of 00:05, 14 August 2020

Typical Problem

Typical Failing Code

export function raceCondition() {
  let xhr = new XMLHttpRequest();
  let statuses = [];
  xhr.open("GET", "http://localhost:3000/ordersStatuses");

  // Success
  xhr.onload = () => {
    statuses = JSON.parse(xhr.responseText);
  };

  let xhr2 = new XMLHttpRequest();
  xhr2.open("GET", "http://localhost:3000/orders/1");

  // Success
  xhr2.onload = () => {
    const order = JSON.parse(xhr2.responseText);
    const description = status.map((t) => {
      if (t.id === order.orderStatusId) {
        return t.description;
      }
    })[0];

    setText("Order Status: ${description}");
  };

  xhr2.send();
}

This may fail because it finishes the second request before the first. I.E. we did not wait for the first request before using the second request.

Callback Pyramid Of Doom

Moving Second Request to after First Request solves the problem but this know as Callback Pyramid Of Doom as each request will indent on the previous request

export function raceCondition() {
  let xhr = new XMLHttpRequest();
  let statuses = [];
  xhr.open("GET", "http://localhost:3000/ordersStatuses");

  // Success
  xhr.onload = () => {
    statuses = JSON.parse(xhr.responseText);

    let xhr2 = new XMLHttpRequest();
    xhr2.open("GET", "http://localhost:3000/orders/1");

    // Success
    xhr2.onload = () => {
      const order = JSON.parse(xhr2.responseText);
      const description = status.map((t) => {
        if (t.id === order.orderStatusId) {
          return t.description;
        }
      })[0];

      setText("Order Status: ${description}");
    };

    xhr2.send();
  };
}

Promises

Introduction

A Promise is "Object that represents the eventual completion (or failure) of an asyncronous operation, and its resulting value" A Promise can have three states

  • Pending
  • Fulfilled
  • Rejected

(Settled/Resolved means either Fulfilled or Rejected)
Note Promises are not lazy, i.e. not like yield in c# they execute immediately.

Standard try catch Promise

This is how to catch a standard promise

export function getCatch() {
  axios
    .get("http://localhost:3000/orders/11")
    .then(({ data }) => {
      setText(JSON.stringify(data));
    })
    .catch((err) => {
      setText(err);
    })
    .finally(() => console.log("Done"));
}

Chaining Promises

Below is an example of chaining Promises. You can catch errors within the code but you would have to make sure you are throwing the appropriate arguments for the next then.

export function chainCatch() {
  axios
    .get("http://localhost:3000/orders/1")
    .then(({ data }) => {
      return axios.get(
        `http://localhost:3000/addresses/${data.shippingAddress}`
      );
    })
    .then(({ data }) => {
      setText(data.my.city);
    })
    .catch((err) => {
      setText(err);
    })
    .finally(() => console.log("Done"));
}

Creating Promises

Promise Arguments

The promise takes something called an executor function

let promise = new Promise((resolve, reject) => 
  {
...
  })

Promise with a request

So we can now create a request assigning the resolve and the reject functions to the functions in XMLHttpRequest.

  let request = new Promise((resolve, reject) => {
    // Create a request
    let xhr = new XMLHttpRequest();

    // Execute the request
    xhr.open("GET", "http://localhost:3000/users/1");

    // Assign onload to the resolve function
    xhr.onload = () => resolve(xhr.responseText);

    // Assign onerror to the reject function
    xhr.onerror = () => reject(xhr.statusText);

    // Do the send
    xhr.send();
  });

  // On success or failure of the request set the text
  request.then((result) => setText(result)).catch((reason) => setText(reason));

Managing a failed 404 request

For a user where it exists the above code works perfectly however when a user does not exist the request is successful but not from an application point of view. Let's improve it.

  let request = new Promise((resolve, reject) => {
    // Create a request
    let xhr = new XMLHttpRequest();

    // Execute the request
    xhr.open("GET", "http://localhost:3000/users/No_Valid");

    // Assign onload to the resolve function
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.responseText);
      } else {
        reject(xhr.statusText);
      }
    };

    // Assign onerror to the reject function
    xhr.onerror = () => reject(xhr.statusText);

    // Do the send
    xhr.send();
  });

  // On success or failure of the request set the text
  request.then((result) => setText(result)).catch((reason) => setText(reason));

Promise All

This is used to send multiple requests. The Promise.All function will waiting until either all' fulfill or one rejects. Here is an example using axios.

  let itemCategories = axios.get("http://localhost:3000/itemCategories");
  let orderStatuses = axios.get("http://localhost:3000/orderStatuses");
  let userTypes = axios.get("http://localhost:3000/userTypes");

  Promise.all([itemCategories, orderStatuses, userTypes])
    .then(([categories, statuses, types]) => {
      setText("");
      setText(JSON.stringify(categories.data));
      setText(JSON.stringify(statuses.data));
      setText(JSON.stringify(types.data));
    })
    .catch((reasons) => {
      setText(reasons);
    });