Checking links stored in an array using JavaScript

I am currently working on a JavaScript function that will iterate through an array of URLs to find a 'pingable' URL and return its index. Here is the code snippet I have so far:

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 am facing a challenge with handling promises within each iteration of the loop. Any advice or guidance would be greatly appreciated.

My attempt involved using a for loop with a break statement to exit once a pingable URL was found. However, breaks are not permitted in this case.

Answer №1

It may be beneficial to enhance the data returned by your function instead of just a boolean value. One approach could be to modify the function so that it accepts a URL and an index, and upon resolving or rejecting the promise, it returns an object containing both the index and the result.

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
      });
    });
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on uploading files and data simultaneously by leveraging ajax, jquery, and spring mvc

How can I use ajax, query, and Spring MVC to upload data along with a file? Below is my modal pop-up, could someone help me with this? <!-- Modal --> <div id="fileUpload" class="modal fade" role="dialog"> <d ...

Can React avoid re-rendering if the setState does not impact the rendering process?

For example, let's consider a scenario where a hook is used to make an API request: function useApi(...) { const [state, setState] = useState({ fetching: false }); useEffect(() => { setState({ fetching: true }); fetch(...) .then( ...

Converting a ReadStream buffer into a permanent file

I've encountered a code block that I'm struggling to work with: fetchFile(file_id) { return new Promise((resolve, reject) => { var mongoose = require('mongoose'); var Grid = require('gridfs-stream'); ...

Creating a jar file for ReactJS in JHipster version 7.1.0

I'm currently working on developing a straightforward app using JHipster. The process involves creating the app by running $jhipster Once the initial setup is complete, I proceed to add some entities by executing $jhipster jdl jhipster-jdl.jdl I ...

Next.js displays an error when attempting to update the `AuthContextProvider` component while rendering the `Login` component

I have developed a basic next.js application that involves user login functionality through a graphql-api. The login process utilizes the react context-API to update the context once the user successfully logs in. Upon successful login, the intention is to ...

Verify whether the element has been clicked prior to deletion

Here is the jquery code I'm working with: $(document).on('focusout', '#element_a', function(e){ $('#element_b').remove(); }); $(document).on('click', '#element_b', function(e){ // additional ...

Slider Volume with jQuery

Struggling to find a solution for this issue. Seeking some assistance. My goal is to create a basic volume slider. So, the orange section represents my volume slider. This is the jQuery code I am using: var mouseIsDown = false; $("#volSlider").on("mou ...

Removing Hash from index.js and index.runtime.js in Parcel using the parcel-namer-hashless plugin: A step-by-step guide

Currently, I am engaged in a TypeScript project where Parcel v2.x is used for bundling. My aim is to eliminate the hash from the output filenames, specifically targeting index.runtime.js. I have implemented the parcel-namer-hashless plugin to achieve this ...

Is there a way to communicate with the Microsoft bot from within the bot itself, ensuring that the message follows the dialog flow and receives the appropriate response?

It would make more sense if the title of this were "how can I ensure the bot responds smoothly in case context is lost or there's a server restart during a user interaction with the bot. It's confusing as it is and I need to break down the planni ...

Show image in ReactJS using flask send_file method

Using Flask's send_file function, I send an image to the client in the following way: @app.route('/get-cut-image',methods=["GET"]) def get_cut_img(): response = make_response(send_file(file_path,mimetype='image/png')) respon ...

Updating a class within an AngularJS directive: A step-by-step guide

Is there a way to change the class (inside directive) upon clicking the directive element? The current code I have updates scope.myattr in the console but not reflected in the template or view: <test order="A">Test</test> .directive("test", ...

Testing the Integration of Angular with Jasmine, utilizing a service that makes real HTTP requests

[Angular version: 2.4.5] As I dive into writing a unit test for an Angular integration component that involves a service using the Angular HTTP library, I'm encountering a challenge with the instantiation of my Service class. Either the Service ends ...

What could be causing Sequelizer to overlook my username?

I have configured a NestJS project and implemented Sequelize to interact with my database. My setup includes a database provider and module that are designed to be used globally. Here is how they are structured: database.module.ts: import {Global, Module ...

Determining the boundaries of the near and far planes for the camera calculations

In my attempt to calculate the near and far plane vertices using THREE.Frustum, I referenced a question on Stack Overflow (Calculate near/far plane vertices) and its corresponding answer (answer link). By combining the information provided, I created a w ...

There seems to be an issue with the type error regarding the return of the mysql2/promise

As I delve into using the mysql2/promise library with Typescript, I've encountered a puzzling issue regarding the return type of the query method. Despite my best efforts, I can't seem to resolve an error in my code. Here is a snippet from my c ...

Strategies for effectively transferring information from a directive template to a controller

I'm currently working on developing a date-picker that consists of two separate date pickers - one for the start date and another for the end date. Each datepicker element generates a template with two input tags. I want to be able to pass data from t ...

Issue: $injector:unpr Angular Provider Not Recognized

I've recently developed an MVC project and encountered an issue regarding the loading of Menu Categories within the layout. <html data-ng-app="app"> . . . //menu section <li class="dropdown" ng-controller="menuCategoriesCtrl as vmCat"> ...

Using jQuery's AJAX function to send a POST request and extracting data from the response

Below is the jQuery AJAX call that I am using: $.ajax({ method: "POST", url: "/Agenda/Template", dataType: 'json', data: { "templateId": templateSelect.options[templateSelect.selectedIndex].value }, c ...

Tips on sorting objects by comparing them to array elements

I have an array called myarrays and an object named obj. I need to filter the object by comparing the elements of the array with the keys of the object. If you want to see the code in action, you can check it out on StackBlitz: https://stackblitz.com/edit ...

Vue.js: In a third-party library, the reference to "this" is coming back as "undefined"

My third-party script contains code in the following format ( function initialMethod(scope, factory) { // 'scope' is undefined when used in Vue // but it works fine in React and Angular } (this, function function1(param1) { ...