I am trying to use something like this write a function in JavaScript that loops through an array of urls. Once a ‘pingable’ url is found the function should return its index number.
function ping(url: string): Promise {
return new Promise((resolve) => {
this.http.get(url, { observe: 'response' }).subscribe(
(response) => {
resolve(response.status === 200);
},
(error) => {
resolve(false);
}
);
});
}
I’m not quite sure how to do this with each iteration having to get results from a promise. Any help is appreciated.
I tried a for loop for each of the urls and use the break statement to exit. However break statements are not allowed.
2
Answers
Try returning more data instead of just a
boolean
. This is untested, but if you pass the URL and the index to this function, then when the promise is resolved or rejected you can return an object with the index and the result in it.You can use the
Promise.all
method to run multiple promises in parallel and return the index of the first URL that returns a successful response.In this function, we first map the array of URLs to an array of promises that use the ping function to check if each URL is pingable. The then method of the promise returns the index of the URL if it is pingable, or -1 if it is not.
We then pass the array of promises to the
Promise.all
method, which runs all the promises in parallel and returns an array of results. The find method is used to find the index of the first URL that returned a successful response (i.e., an index that is not -1).Alternatively, you can use
async/await
to wait for the result of each ping call before moving on to the next URL.