Since Javascript Promises promise a lot. One of the things I would like to know is how to make an Ajax request through promises , in pure Javascript, without having to go through third-party libraries.
It would be a request that properly handles the success or failure of the request made, indicating the result obtained or an error message.
The new
API Fetch
one allows making "AJAX" calls (Request
) and implementsPromises
by default.Usage example:
More info:
* David Walsh - fetch API
* Google Developers - Introduction to fetch()
* Github - fetch polyfill
This would be an example of an Ajax call function, using Promises.
With our function
myAjax()
we can make requests via ajax and obtain the response, or the error code, transparently, without the need for libraries such as jQuery.As indicated in the link below:
Which means that calling Ajax via Promises will be much easier in the future. Until that arrives, we can use a function like this, passing the method (
GET, POST
) and the url of the REST service, API, or a php, json or other file of our applications to the function as a parameter.Links