skip to Main Content

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


  1. 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.

    interface IPingableResponse {
      index: number;
      pingable: boolean;
    }
    
    ping(url: string, idx: number): Promise<IPingableResponse> {
      return new Promise<IPingableResponse> ((resolve) => {
        this.http.get(url, {
          observe: 'response'
        }).subscribe((response) => {
          resolve({
            index: idx,
            pingable: response.status === 200
          });
        }, (error) => {
          resolve({
            index: idx,
            pingable: false
          });
        });
      });
    }
    
    Login or Signup to reply.
  2. 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.

    function findPingableUrlIndex(urls: string[]): Promise<number> {
      const promises = urls.map((url, index) =>
        ping(url).then((result) => (result ? index : -1))
      );
    
      return Promise.all(promises).then((results) =>
        results.find((index) => index !== -1)
      );
    }
    

    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.

    async function findPingableUrl(urls: string[]): Promise<number> {
      for (let i = 0; i < urls.length; i++) {
        const isPingable = await ping(urls[i]);
        if (isPingable) {
          return i;
        }
      }
      return -1; // no pingable URL found
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search