Javascript async: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 63: Line 63:
}
}
</syntaxhighlight>
</syntaxhighlight>
===Promise===
===Promises===
A Promise is "Object that represents the eventual completion (or failure) of an asyncronous operation, and its resulting value"
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
A Promise can have three states
Line 69: Line 69:
* Fulfilled
* Fulfilled
* Rejected
* Rejected
(Settled/Resolved means either Fulfilled or Rejected)
(Settled/Resolved means either Fulfilled or Rejected)<br>
'''Note''' Promises are not lazy, i.e. not like yield.
'''Note''' Promises are not lazy, i.e. not like yield.

Revision as of 04:30, 13 August 2020

Introduction

Example Code

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

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.