How to send multiple requests using axios
Storyblok is the first headless CMS that works for developers & marketers alike.
Performing multiple HTTP requests with Axios
In this article, we will see how you can achieve concurrent execution of HTTP calls by taking advantage of the Promise feature. First, make sure you have installed Axios:
Now we installed Axios, let's start with a small task and send one request using Axios. In the example, we will set one URL for accessing the Content Delivery API (version 2) provided by Storyblok.
First, we import Axios and define the API/URL we want to load from. Then, we can call the
get() method. Because the
get() method is asynchronous, a
Promise object is returned. With the
Promise object, we can set the callback for managing the fulfilled response via the
then() method. To manage also the error, we can use the
axios returns a Promise, we can go for multiple requests using
Then, we define the different URLs we want to access.
We defined a list of URLs as an array. Using
map() method, we call multiple
axios.get() for each URL in the array. Then, in the requests array, we have the list of the promises, one Promise object for each request sent. Then with
axios.all() we obtain all the fullfilled responses from all the requests. All the requests are sent in parallel.
You can write your code for performing multiple parallel requests:
In the code we followed some steps:
apiPluginfrom our SDK
- Define the set of URL/path as array;
- initializing the SDK via
storyblokInit()using the token for your space;
- Calling the
storyblokApi.get()method for all the URLs/paths set at point 2 (avoiding using the await)
- Manage all the promises returned by point 4 via
Executing multiple HTTP calls concurrently can reduce the total response time, improving the performance of the execution of the logic you implement.
Curious to keep learning?
Check out Storyblok, bringing you the latest tech solutions to stay on top of your game