A brief introduction to Javascript Fetch Api
According to MDN; Fetch Api provides an interface for fetching(Getting, Requesting) for resources.
If you are familiar with XMLHttpRequest, then you already have a clue on what I’m talking about as it performs the same function but in a more powerful and flexible way. The Fetch Api make use of Promise which is another powerful tool.
Promise are used when working with asynchronous codes. They are used instead of a Callback Function.
Callbacks are function that are be run or executed after another function
To demonstrate this, We are making an HttpRequest. Our http method takes in four parameter
The URL, Method, successCallback and errorHandler.
To mimic a real request, we would use a setTimeout of about 1 second to help delay our response.
In our function we define a variable, so if our request is successful, the succcessCallback function is executed else the errorhandler callback will be executed. Run the code and you will get the result as expected
Using Promise
Promise simplify our request by removing the successCallback and errorHandler callbacks, Then create a new Promise which takes in a single function with two parameter, Resolve and Reject
Resolve is executed when our request is successful and Reject when there is an error.
See the code snippet below to see how promise work.
One of the advantage of using a promise over callback is that it prevents our code from uncaught exception error and it also allow us to use the return statement in our code, something that can not be done with callbacks.
Enough of callback and promise, Back to Fetch
Why Use the Fetch Api
Using the Fetch Api makes asynchronous request easy and also makes our code simple and neat.
Using fetch api involves the following syntax
Lets play with some code
Our fetch takes in the url were making the request to, on success, it returns a promise where we transform our data into json format.If that is also succeful, it returns another promise where we now have to handle our data in anyway we like to handle it.
Conclusion
The Fetch Api make asynchronous request easy.