Exploring Fetch API with Promise.all

I have successfully implemented a functionality that fetches data from two URLs and performs an action only when both requests are successful. However, I am curious if there is a more efficient and succinct way to achieve the same result.

Helper functions

let checkStatus = (response) => {  
  if (response.ok) {  
    return Promise.resolve(response)  
  } else {  
    return Promise.reject(new Error(response.statusText))  
  }  
}

let parseJson = (response) => response.json();

Requests

let urls = [
    'http://localhost:3000/incomplete',
    'http://localhost:3000/complete'
]

let promises = urls.map(url => {

    return fetch(url)  
    .then(checkStatus)  
    .then(parseJson)  
    .then(data => Promise.resolve(data))
    .catch(error => Promise.reject(new Error(error)));

});

Promise.all(promises).then(data => {
    // Perform actions with the data
}).catch(error => {
    console.log('Oops, something went wrong!', error);
});

Answer №1

// Fetching test JSON data from https://jsonplaceholder.typicode.com
var urls = [
  'https://jsonplaceholder.typicode.com/todos/1',
  'https://jsonplaceholder.typicode.com/todos/2',
  'https://jsonplaceholder.typicode.com/posts/1',
  'https://jsonplaceholder.typicode.com/posts/2'
];

// Creating Promise for each URL fetch
var requests = urls.map(function(url){
  return fetch(url)
  .then(function(response) {
    // throw "uh oh!";  - test a failure
    return response.json();
  })  
});

// Resolving all promises
Promise.all(requests)
.then((results) => {
  console.log(JSON.stringify(results, null, 2));
}).catch(function(err) {
  console.log("returns just the 1st failure ...");
  console.log(err);
})
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

Answer №2

const websites = [
    'http://example.com/incomplete',
    'http://example.com/complete'
]
const processData = (response) => response.json()
const checkStatus = (response) => response.ok ? Promise.resolve(response) : Promise.reject(new Error(response.statusText))
const fetchWebsiteData = url => fetch(url).then(checkStatus).then(processData)
const handleErrors = error => { console.log('Oops, an error occurred!', error) }
const displayData = data => { console.log('Fetched data: ', data) }

Promise.all(websites.map(fetchWebsiteData))
  .then(displayData)
  .catch(handleErrors)

Answer №3

Utilize fetchOk for more user-friendly error messages, and implement destructuring to easily access the results:

let fetchOk = (...args) => fetch(...args)
  .then(res => res.ok ? res : res.json().then(data => {
    throw Object.assign(new Error(data.error_message), {name: res.statusText});
  }));

Promise.all([
  'http://localhost:3000/incomplete',
  'http://localhost:3000/complete'
].map(url => fetchOk(url).then(r => r.json()))).then(([d1, d2]) => {
  // implement actions with d1 and d2
}).catch(e => console.error(e));


// manage stackoverflow's dysfunctional error logger.
var console = { error: msg => div.innerHTML += msg + "<br>" };
<div id="div" style="white-space: pre;"></div>

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

Error: Unable to locate the reference

Having trouble with my JavaScript code not recognizing the linked .js files I added. I initially linked them through CodePen, but manual references don't seem to be working. Attempted suggestions from this page Why does jQuery or a DOM method such as ...

Ways to showcase Material-UI Grid components without using cards

I initially used Material-UI grid items for spacing adjustments, but now they are displaying as cards. I would prefer them to be invisible like before, but the documentation doesn't provide a solution for this issue. Any assistance would be greatly ap ...

In your experience, what's the most efficient method you've come across for editing tags?

Currently, I am working on implementing a feature that allows users to edit the list of tags displayed next to each link on a website. This includes adding, removing, and modifying tags. I am searching for an efficient way to make this process user-friend ...

Tips for sending multiple HTTP requests to a single page from a single client

Is there a way to run multiple AJAX calls on the same page from the same client without them getting queued by the server? The calls are starting correctly, but it seems like the server is executing only one request at a time. I've checked the start ...

The onclick handler fails to function following the injection of html using jquery AJAX

After using ajax to inject HTML into my page, the onclick handler on a specific part of that injected HTML does not seem to be functioning... Specifically, I am referring to this image... < img class="close_row" src="img/close.gif"/> In jQuery, I ...

Get rid of the horizontal scroll bar and expand the width of the table

Normally, Tabulator limits the maximum width of the table and adds a horizontal scroll bar at the bottom. Is there a way to eliminate this scroll bar and make Tabulator expand the width of the table instead (resulting in the horizontal scrollbar appearin ...

What is the reason behind only the final input value being shown on the screen?

I'm encountering an issue with my input fields. I have a total of five input fields. After filling all of them and clicking the button to display them on the screen, only the last one I entered is shown in all places... (let me know if this explanatio ...

Send an AJAX parameter and retrieve it on the expressjs server side of the application

It seems like there's a crucial piece missing here. Let's begin with an AJAX call that can be executed in the <script> tag to send data to the backend. It might look something like this: function changeDom(){ console.log('connectin ...

The replace method for strings in JavaScript does not function properly on mobile devices

I encountered an issue with the string replace method I implemented on my website. Upon checking the page using the web browser on my Android phone, I noticed that it was not functioning as intended. Here's a snippet of the code: /*The function is ...

What is the most effective method for accurately tallying the number of matches in a Datalist using the Input value as a reference

I have set up a datalist element with an associated input element for autocompletion in modern browsers: HTML code <input type="search" id="search" list="autocomplete" /> <datalist id="autocomplete"> <option value="c++" /> < ...

The Navbar is throwing a TypeError because it is unable to retrieve the property 'classList' of null

I am currently experimenting with building a navbar in HTML that has the capability to dynamically switch pages without changing links using href. The method I'm employing to achieve this involves adding a classList of is-active to the div elements wi ...

Content refuses to show up on my social networking website project when Ajax is employed

I've been working on a Social Media website for a major project, and I recently implemented Ajax to load posts. However, I'm facing an issue where the content is not displaying on the index page after implementation. My goal is to load 10 posts a ...

I am having trouble getting the jsTree ajax demo to load

I am having trouble running the basic demo "ajax demo" below, as the file does not load and the loading icon continues to churn. // ajax demo $('#ajax').jstree({ 'core' : { 'data' : { ...

What could be causing my jQuery script to not load properly on the first attempt?

I have a jQuery script set up on this particular webpage just before the ending body tag. Here is the script: <script> $(document).ready(function(){ var demomain = $(".demo-bg section"); var demomainW = demomain.height()+ 150 ...

Arrange a div element within another div by utilizing the fixed positioning property, while also accounting for any potential "white space

Can someone help me figure this out: I currently have this much progress: http://jsbin.com/apikiw/3/edit#preview The issue I'm facing is that I am unable to insert it between the <p /> tags due to its dynamic nature... any solutions or suggest ...

AJAX causes PHP file to receive empty values from HTML form

As a newcomer to AJAX, I am aiming to create a search feature that retrieves data from a database based on user input. Despite my efforts to debug the code multiple times, I have been unable to resolve the issue. Any assistance would be greatly appreciated ...

customizing highcharts title within a popup window

Is there a way to dynamically set the title of a Highcharts chart from an element? Check out my code snippet below: $(function () { var chart; $('#second-chart').highcharts({ chart: { type: 'bar' }, subtitle: { ...

The jQuery Ajax call encountered an error when trying to make a GET request to a different

My goal is to make a request to a different domain using the following URL: http://ccv.viatelecom.com/services/?item=viacall&aid=XXXX&gid=XXXX&sid=XXXX&&num=XXXXXX To achieve this, I have implemented an Ajax request like so: $.ajax({ ...

The form fails to submit when the page automatically reloads

I have a PHP web application that requires certain variables on this page to be automatically refreshed. To achieve this, I have moved the processing to another page called "test.php", which is loaded into this div every 10 seconds. <script type="text ...

Most effective method for detecting null or undefined values

Curious to know, what is the most efficient method for verifying if something is null or undefined within JSON arrays or objects in general? I have been utilizing if (value !== null && value !== undefined) { // Value isn't null or undefine ...