简体   繁体   中英

How to call web service endpoints one after other?

I want to implement a function in JavaScript which calls a series of web service endpoint and checks for a value in the response of the API call. I need to achieve it in a way that the first endpoint page is called first then the there would be a filter method to filter out the specific object from the response. If the object is found, this process should break and the object must be returned. However if the object is not found in the first endpoint, then the second endpoint must be called and the same process is repeated until the object is found.

The Web service endpoint that I am working on is:

https://jsonmock.hackerrank.com/api/countries?page=1

This API returns a list of country data. Here the value of page query varies from 1 to 25. I need to call the endpoint and check for a specific country from 1 to 25 until the country object is found.

I tried achieving this using JavaScript Promise and Fetch API and couldn't think of a way to call the APIs one after the other.

I am really looking forward for your answer. Thank you in advance.

You can use async and await for this:

 async function findCountry(country) { for (let page = 1; page < 26; page++) { console.log("page = " + page); // for debugging only let response = await fetch("https://jsonmock.hackerrank.com/api/countries?page=" + page); let {data} = await response.json(); let obj = data.find(obj => obj.name == country); if (obj) return obj; } } let country = "Belgium"; findCountry(country).then(obj => { if (obj) { console.log("The capital of " + country + " is " + obj.capital); } else { console.log("Could not find " + country); } });

If you know that the data is sorted by country name, then you could reduce the average number of requests by using a binary search.

Here's a way that you can do it.

 const url = 'https://jsonmock.hackerrank.com/api/countries' const fetchFromApi = async (countryName, page) => { const res = await fetch(`${url}?page=${page}`) return await res.json() } const getCountryFromResults = (countryName, data) => { const country = countryName.toLowerCase() return data.find(({name}) => name.toLowerCase() === country) } const findCountry = async (countryName) => { let page = 1; let totalPages = 1; while(page <= totalPages) { const res = await fetchFromApi(countryName, page); if(totalPages < res.total_pages) { totalPages = res.total_pages } const country = getCountryFromResults(countryName, res.data) if(country){ return country } page = page + 1 } } ( async () => { console.log(await findCountry("Afghanistan")) console.log(await findCountry("Argentina")) } )()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM