Exploring the power of Chained Promise.allSettled

Currently, I am working on a project that involves using a basic for loop to create an array of IPs for fetching. My goal is to verify that the response.status is 200 (though I have not yet implemented this), and then filter out only those IPs that return a status of 200.

I initially attempted this task using Promise.all, but encountered an issue where if one request failed, all requests were rejected. As a result, I have come up with the following solution:

async function example() {
    var arr = [];
    for (let i = 4; i <= 255; i++) {
        var ip = 'http://172.16.238.' + i.toString() + ':443';
        arr.push(ip);
    }
    Promise.allSettled(arr.map(u=>fetch(u))).then(responses => Promise.allSettled(responses.map(res => res.text()))).then(texts => {fetch('https://testing.com', {method: 'POST', body: texts})})
}
example()

However, I'm encountering an error stating that res.text() is not a function when used with allSettled. Additionally, I'm unclear on how to go about checking the status of each response. Since I am mapping the URL to each fetch and then mapping a response to its text, should I perform the status check during the second mapping? The concept of mapping is a bit perplexing to me.

Answer №1

allSettled function doesn't provide an array of resolved values, but instead returns an array of objects with properties like status, value, and reason. To access the resolved value, you need to use .value.

If there is no error, a single call to allSettled suffices - make sure to call .text within the first callback.

function example() {
    var arr = [];
    for (let i = 4; i <= 255; i++) {
        var ip = 'http://172.16.238.' + i.toString() + ':443';
        arr.push(ip);
    }
    Promise.allSettled(arr.map(
        u => fetch(u)
            .then(res => { if (res.ok) return res.text(); })
    ))
        .then(results => {
            const texts = results
                .filter(result => result.status === 'fulfilled' && result.value)
                .map(result => result.value);
            fetch('https://testing.com', { method: 'POST', body: texts })
                // ...
        })
}

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

Utilizing JSON Data with JQuery: A Beginner's Guide

I am using a setTimeout function to reload another function every 5 seconds. The update_list function is responsible for rendering entrances in a view. However, when there are many entrances and you have scrolled down, the list empties and reloads every e ...

When a user clicks a button, modify a section of the URL and navigate to

I've been searching everywhere for a solution to this issue, but I just can't seem to find it. I'm hoping someone here can help me out. In a bilingual store, I need a way to redirect users to the same product on a different domain when they ...

The chosen state does not save the newly selected option

Operating System: Windows 10 Pro Browser: Opera I am currently experiencing an issue where, upon making a selection using onChange(), the selected option reverts back to its previous state immediately. Below is the code I am using: cont options = [ ...

Assign a value to the input field based on changes made in another input field

I am brand new to the world of JavaScript and currently grappling with setting a value in an input field based on the onchange event of another input field. Here is my code sample for input field 1: <input type='text' onchange='methodTh ...

The pattern() and onkeyup() functions are unable to function simultaneously

When trying to display a certain password pattern using regex while typing in the fields, I encountered a problem. The onkeyup() function works for checking if both passwords match, but it causes the pattern info box not to appear anymore. I'm curiou ...

"Learn the steps to access a JSON file directly from a URL within a Next.js

My goal is to upload a JSON file to the server from a URL, open it, parse it, and display its features on Google Maps. However, I am encountering an error with the "fs" library preventing me from opening the file. Below is the code: "use client" ...

Navigating through Sails.Js: A Guide to Implementing Pagination

Looking to implement paginated tables in your application using sails.js, mongodb, and waterline-ORM? Wondering if there is a recommended method for pagination in sails.js? ...

(Is it even necessary to use a timezone library for this straightforward scenario?)

As I delve into the realm of time zones for the first time, I've heard tales of how challenging it can be for developers. To ensure I am on the right track, I am posing this question as a safeguard to make sure nothing is overlooked. My scenario is q ...

Remove the JSON object by comparing IDs between two JSON objects in JavaScript or Node.js, deleting it if the ID is not found

let data = fetchData(); let anotherData = getAnotherData(); let result = data.reduce((accumulator, current) => { if (!accumulator[current.system.name]) { accumulator[current.system.name] = {}; } let detailsObject = {}; Object.keys(current. ...

In Node JS, the variable ID is unable to be accessed outside of the Mongoose

When working with a Mongoose query, I encountered an error where I am trying to assign two different values to the same variable based on the query result. However, I keep getting this error: events.js:187 throw er; // Unhandled 'error' ev ...

With Ionic, you can use one single codebase for both iPad and iPhone

I currently have a complete app developed using ionic and angularjs that is functioning well on iPads and Android devices. Now we are looking to launch it for iPhones and Android smartphones with some design modifications. Is there a method to achieve th ...

Changing the position of the icon in the bootstrap validator

I'm currently attempting to validate form fields in a web project. The goal is to achieve a specific result, similar to the image below: https://i.stack.imgur.com/EVeJf.png While I have made progress with a simple solution that almost meets the requi ...

Obtaining values from event listeners in Vue.js across different methods

Looking for guidance on the code snippet provided below. Is there a way to assign the value of "e.detail.name" to "nodeName," and then access it in a different method within the component for an API request? data() { return { nodeName: '' ...

Tips for implementing ngChange within a personalized directive

Looking to create a directive for a toggle button, here is the code I want to include in the directive: <div class="toggle-button" ng-class="{true: toggleTrue === true, false: toggleTrue === false}"> <button class="true" ng-click="toggleTrue ...

Dealing with the error "Type 'date[]' is not assignable to type '[date?, date?]' in a React hook

I'm attempting to assign a date range but encountering an error that states: Type 'Date[]' is not assignable to type '[Date?, Date?]'. Types of property 'length' are incompatible. Type 'number' is not assignab ...

Is it possible to have the ShowHide plugin fade in instead of toggling?

I'm currently utilizing the ShowHide Plugin and attempting to make it fade in instead of toggle/slide into view. Here's my code snippet: showHide.js (function ($) { $.fn.showHide = function (options) { //default variables for the p ...

Showcase information from APIs using Vue.js

I am facing an issue where I am able to fetch data correctly from the API, but I am unable to display it. When I manually input items, they are displayed, but the items fetched from the API remain invisible. I even attempted to move the API call directly i ...

How can data be passed from a directive to a controller in Angular?

I am currently working on implementing a directive pagination feature and I need to pass the current page number from the directive to a controller in order to run a specific function with this argument. However, I keep getting an 'undefined' err ...

I find the SetInterval loop to be quite perplexing

HTML <div id="backspace" ng-click="deleteString(''); decrementCursor();"> JS <script> $scope.deleteString = function() { if($scope.cursorPosVal > 0){ //$scope.name = $scope.name - letter; ...

Tracking changes in real time and calculating the sum with AJAX, PHP, and MySQL for efficient processing

Initially, I kindly request you to read this until the end. I am in dire need of assistance with my problem as I have searched for solutions but still remain clueless. Referring to the image provided, the first 'Product & Total Product' element ...