Autonomía digital y tecnológica

Código e ideas para una internet distribuida

Linkoteca. Promises


The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON.

const myList = document.querySelector("ul");
const myRequest = new Request("products.json");

fetch(myRequest)
  .then((response) => response.json())
  .then((data) => {
    for (const product of data.products) {
      const listItem = document.createElement("li"); 
      listItem.appendChild(document.createElement("strong")).textContent = product.Name; 
      listItem.append(` can be found in ${product.Location}. Cost: `); 
      listItem.appendChild(document.createElement("strong")).textContent = `£${product.Price}`; 
      myList.appendChild(listItem);
    }
  })
  .catch(console.error);

Asynchronous requests will wait for a timer to finish or a request to respond while the rest of the code continues to execute. Then when the time is right a callback will spring these asynchronous requests into action.

Generators

One use for generators is that they allow you to have async code looking like sync.

Instead of returning with a return, generators have a yield statement. It stops the function execution until a .next is made for that function iteration. It is similar to .then promise that only executes when resolved comes back.

Async/Await

This method seems like a mix of generators with promises. You just have to tell your code what functions are to be async. And what part of the code will have to await for that promise to finish.

The async and await keywords are a great addition to Javascript. They make it easier to read (and write) code that runs asynchronously. That includes things like:

API calls (using fetch or a library like axios);
Timeouts (though these need a little extra work); or
Reading/writing files if you’re using NodeJS.

I’m going to assume you’re familiar with Promises and making a simple async/await call. Where it can get tricky is when we have a whole bunch of tasks in an array. You might run through the array expecting calls to run one-by-one. But instead, they run through all together and don’t wait for each individual item to resolve. Or, you might find yourself with the opposite problem. You run through your array in a loop, wanting them to run in parallel. But instead, it waits and does them one by one. And sometimes, you try something and it doesn’t work at all. The program just continues after the loop instead of waiting until the calls are all done. You end up wondering if there’s something you’re missing.

Promises simplify deferred and asynchronous computations. A promise represents an operation that hasn’t completed yet.

A promise can be:

fulfilled – The action relating to the promise succeeded
rejected – The action relating to the promise failed
pending – Hasn’t fulfilled or rejected yet
settled – Has fulfilled or rejected

Promise is used to overcome issues with multiple callbacks and provide better way to manage success and error conditions.

Promise is an object which is returned by the async function like ajax. Promise object has three states

pending :- means the async operation is going on.
resovled :- async operation is completed successfully.
rejected :- async operation is completed with error.

There are two parts using a promise object. Inside async function (Part1) and where its called (Part2).

Part1 — Inside Async function,

Promise object is created.
Async function returns the promise object
If async is done successfully, promise object is resolved by calling its resolve method.
If async is done with error, promise object is rejected by calling its rejected method.

Part2 — Outside Async function

Call the function and get the promise object
Attach success handler, error handler on the promise object using then method

Cross Domain Call

By Default, AJAX cannot make cross domain call, browser will reject the calls to the different domain. In order to make cross domain call there are two options

Using CORS
Using JSONP

Both the options requires some server changes. It cannot be done purely using javascript.

CORS is the new way to deal with cross origin AJAX request. github api are CORS enabled. In order to enable CORS, response should contain Access-Control-Allow-Origin header with the domain value or * to work for all. Github has set as *.

JSONP can also be used if CORS cannot be enabled by server or for old browsers. JSONP actually uses script tag to get the data from the server. Script is allowed to be fetched from any domain, So in JSONP, we need to create a script with the url as src and the server has to wrap the response in a callback function. Response sent by server is actually a javascript code which contains data inside a wrapper function. In JSONP, there is no ajax call being made.

Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

A common need is to execute two or more asynchronous operations back to back, where each subsequent operation starts when the previous operation succeeds, with the result from the previous step. We accomplish this by creating a promise chain.

Promises solve a fundamental flaw with the callback pyramid of doom, by catching all errors, even thrown exceptions and programming errors. This is essential for functional composition of asynchronous operations.