Autonomía digital y tecnológica

Código e ideas para una internet distribuida

Linkoteca. AJAX


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.