When it comes to working with APIs in JavaScript, understanding how to manage requests asynchronously is crucial. Asynchronous operations help improve application performance and user experience by allowing code execution to continue while waiting for responses. Promises are a key feature in JavaScript for handling these operations elegantly.
Today, we'll learn how to create a promise-based function to make API requests using the Fetch API. Let's get started!
The Fetch API is modern and widely used for making network requests in JavaScript. It returns a Promise that resolves to the Response object representing the response to the request.
Promises provide a cleaner way to handle asynchronous code compared to traditional callback functions. They allow you to chain .then()
methods for success and .catch()
methods for handling errors, making your code more readable.
We will create a function called apiRequest
that can handle GET and POST requests. This function will take care of sending the request to the specified URL and processing the response.
Here’s a simple example of how we can structure our apiRequest
function:
function apiRequest(url, method = 'GET', data = null) { const options = { method: method, }; // If there is data to send (in case of POST requests), stringify it if (data) { options.headers = { 'Content-Type': 'application/json' }; options.body = JSON.stringify(data); } // Return the fetch promise return fetch(url, options) .then(response => { // Check if the response is okay (status in the range 200-299) if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } // Parse the response body as JSON return response.json(); }); }
Function Parameters: The apiRequest
function takes three parameters:
url
(string): The URL to which the request is sent.method
(string): The HTTP method to use (GET, POST, etc.), with a default value of 'GET'.data
(object): An optional payload for POST requests.Fetch Options: We create an options
object to define the request method and any headers. If data
is provided, we set the Content-Type
header to application/json
and convert our data object to a JSON string.
Making the Request: The fetch
function is called with the URL and options. It returns a Promise.
Handling the Response: Inside the first .then()
, we check if the response is OK (status code 200-299). If not, we throw an error. If it is okay, we parse the response as JSON and return it.
Now, let’s see how we can use our apiRequest
function to fetch data from a sample API. We will use the JSONPlaceholder API, which is a great tool for testing.
// Example of a GET request apiRequest('https://jsonplaceholder.typicode.com/posts') .then(data => { console.log('GET Response Data:', data); }) .catch(error => { console.error('Error:', error); }); // Example of a POST request const newPost = { title: 'foo', body: 'bar', userId: 1, }; apiRequest('https://jsonplaceholder.typicode.com/posts', 'POST', newPost) .then(data => { console.log('POST Response Data:', data); }) .catch(error => { console.error('Error:', error); });
With the promise-based apiRequest
function implemented, we can now easily handle both GET and POST requests. The function is versatile and makes our code much cleaner and easier to maintain. The ability to chain promises allows us to manage asynchronous responses without the dreaded callback hell.
14/09/2024 | VanillaJS
22/10/2024 | VanillaJS
15/10/2024 | VanillaJS
22/10/2024 | VanillaJS
25/07/2024 | VanillaJS
22/10/2024 | VanillaJS
22/10/2024 | VanillaJS
21/07/2024 | VanillaJS
14/09/2024 | VanillaJS
12/09/2024 | VanillaJS