The Promise.all catch clause does not function properly

I am attempting to load multiple text files using fetch requests with Promise.all. Here is my implementation:

////////////////////////////////////////
const loadTextFiles = (allUrls, textUrls) => {
    const requests = textUrls.map(url => fetch(url));
    return Promise.all(requests)
           .then(responses => Promise.all(
                 responses.map(response => response.text())
           ))  
           .then(texts => texts.forEach(
               (text, i) => allUrls[textUrls[i]] = text
           ))  
           .catch(err => {
               // log("HERE");
               throw exception("networkLoader",
                               "loadTextFiles",
                               `error in loadTextFiles: ${err.toString()}`);
           });
}; 

The arrays allUrls and textUrls contain the URLs of all resources (files with any extension) and text resources (files with .txt extension) respectively. The textUrls array is constructed from the allUrls array. After fetching the data, it is stored inside the allUrls array. For example, if

allUrls = [ "image.png", "essay.txt" ]
, then
textUrls = [ "essay.txt" ]
. When calling the loadTextFiles function:

await loadTextFiles(allUrls, textUrls);

You can access the contents of "essay.txt" by accessing allUrls["essay.txt"]. Everything works well as long as all text files exist and can be retrieved. The issue arises when there are problems in retrieving the files. Even though I have a catch block to handle errors in Promise.all, it does not seem to work. For instance, when requesting a file that does not exist like fileThatDoesNotExist.txt, I receive a 404 (Not Found) error in the browser console but the code inside the catch block does not execute. I have even tested it with a custom log function, which also does not run. How can I catch the error and re-throw it?

Edit: To clarify, when mentioning catching the error, I mean detecting the 404 error and throwing an exception (such as a custom exception object).

Answer №1

To find the solution to this query, we can follow these steps:

const loadTextFiles = (allUrls, textUrls) => {
    const requests = textUrls.map(url => fetch(url));
    return Promise.all(requests)
           .then(responses => Promise.all(
                 responses.map(response => {
                    if (response.ok) {
                        return response.text();
                    }
                    throw exception("networkLoader",
                                    "loadTextFiles",
                                    `couldn't load ${response.url}`);
                 })
           ))
           .then(texts => texts.forEach(
               (text, i) => allUrls[textUrls[i]] = text
           ))
           .catch(err => {
               if (exception.isException(err)) {
                   throw err;
               }
               throw exception("networkLoader",
                               "loadTextFiles",
                               `error: ${err.toString()}`);
           });
};     

We verify each fetch response by examining its ok status, and an error is raised if it returns 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

What is the best way to update the color of a v-select component?

https://i.sstatic.net/6VOIo.png Currently utilizing Vuetify for my project <v-select id="makeMeBlue" dense outlined :items="form.values.urlTypes" label="Single or Multi URL" v-model="form.values.urlType" ...

What could be causing the sporadic functionality of my jQuery image resizing code?

Seeking help for an issue I am facing with my jQuery code. I have been trying to scale a group of images proportionally within an image carousel using jCarousel Lite plugin. However, the resizing code seems to work randomly and I can't figure out why. ...

Is it possible to achieve a Column Chart output in R/Highcharts?

Looking to utilize highchart to create a chart with columns stacked within each other for different countries. https://i.sstatic.net/2p1uM.png I want the smaller column to be nested inside the larger one for each country. Any suggestions on how I can ac ...

New to JSON: Why is my variable returning as undefined?

Embarking on my first JSON project has brought some challenges that I am struggling to overcome. Here's the task at hand. I have created a basic scraper using Apify.com to extract data from a specific website. The data is presented in JSON format, an ...

What is the best method for finding the value of an element?

Here is the snippet of code that I'm working with: if($('span').text().indexOf("t")){ console.log($('span').text()); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <sp ...

Issue with Angular UI Router arises when state cannot be resolved upon page reload

I'm currently facing an issue with routing that I mentioned in the title. Even though my route is functioning, it encounters difficulties when the page is reloaded. Below is the routes object: { state: 'locations', config: { ...

Extract a value from a promise nested within Webdriver

My goal in the test code is to achieve the following: it('Updates label text', function(done) { page.testLabelText(); assert.equal(page.testLabelText().pageLabel, page.testLabelText().iFrameLabel); done(); }); In my page object, here i ...

Combining Framer Motion with Next.js: Resolving conflicts between layoutId and initial props in page transitions

As I work on creating smooth image page transitions using Framer Motion and Next.js with layoutId, I've come across a challenge. Here is my main objective: The home page displays an overview with 3 images When an image is clicked, the other images f ...

Troubleshooting Issue: Next.js and Tailwind CSS causing Sanity HTML Content to Display Incorrectly

We have integrated Sanity, Next.js, and Tailwind CSS into our current project. Recently, a field named 'raw_html' has been added to the Sanity content, which includes some HTML code along with sample data. <div class="p-4 bg-gray-100 roun ...

Declare the variable as a number, yet unexpectedly receive a NaN in the output

I'm facing an issue with a NaN error in my TypeScript code. I've defined a variable type as number and loop through an element to retrieve various balance amounts. These values are in the form of "$..." such as $10.00 and $20.00, so I use a repla ...

Numerous conditionals placed in the <head> section of the document

I need to run a script in all browsers except versions of IE below 9. The conditional statement for IE looks like this: <!--[if gt IE 8]> JavaScript code goes here <![endif]--> However, this code will only execute in IE9 and not in any ot ...

assigned to a variable and accessed in a different route

Why does the "res.username" variable return as undefined in the second route even though my user needs to login before accessing any route? router.post('/login', passport.authenticate('local'), function(req, res) { res.username = r ...

Rearrange the arrangement of the array of objects

I am working with an array of objects that looks like this: [{ "Germany": "text", "Brazil": "50.00" }, { "Germany": "1000.00", "Brazil": "1100.00" }, { "Germany& ...

Attempting to utilize JavaScript in order to reset a text input field

I'm having trouble clearing a text field using this function. The alert is working but the field remains unchanged. What could be the issue? This function is designed to work on any text field. <!DOCTYPE html> <html> <head> ...

Tips on how to update the status variable to true depending on the index value

Once I click on the close button, the value immediately changes to "Fruit." How can I achieve this? For instance: Apple close Grapes close Pineapples close Alternatively, is there a way to set the state of "cancel" to true ...

Font in Three JS not loading properly

I'm attempting to use TextGeometry in my project to incorporate text. var shape = new THREE.TextGeometry( 'Hello, World!', { size: 60, height: 20, curveSegments: 3, font: 'helvetiker', weight: ' ...

employing the dimensions of the browser's viewport within a conditional statement

Recently, I came across this JavaScript code that helps in fetching the current viewport size: //get viewport size var viewport = function(){ var viewport = new Object(); viewport.width = 0; viewport.height = 0; // the more standards compliant browsers (m ...

Convert an array to a string in ES6 without using commas

Is there a way to transform a list of errors into a tooltip-friendly format without adding commas between each item? The list is being displayed with an unwanted comma after every li element. I suspect this issue arises from the use of errors.map(error =& ...

Error: Unable to access undefined properties while trying to read 'add' value. Issue identified in the code related to "classlist.add" function

I am currently facing an issue where I receive the error message: Uncaught TypeError: Cannot read properties of undefined (reading 'add') when trying to add a class to a div using a button. After researching on Stack Overflow, I stumbled upon a ...

Using git mv in VSCode does not automatically adjust TypeScript / JavaScript import paths

Is there a way to successfully move a typescript file in VSCode to achieve both of the following: Ensure Git acknowledges the file continuity Have VSCode update the parent files' import statements I have tried two methods, but each one falls short: ...