Troubles with Promise.all and json() in JavaScript causing errors being logged as "invalid function"

I'm experiencing some difficulties with the "Promise.all" method. Essentially, I have an array of URLs (here is a simple one if you want to test it:

const urlArray = [
  "https://coverartarchive.org/release/985adeec-a1fd-4e79-899d-10c54b6af299",
  "https://coverartarchive.org/release/4c54ee58-86df-3ba5-aaad-6b284293141b",
  "https://coverartarchive.org/release/cd8e5736-ec8c-3c4d-a231-ac097877d87a",
  "https://coverartarchive.org/release/b9b7641f-9389-342e-8be9-e463bd52fdb9",
  "https://coverartarchive.org/release/b6206cad-15eb-3a95-b67e-1f49849e5fbd",
  "https://coverartarchive.org/release/db425753-965f-4881-955b-8cd3ef65d1e6",
  "https://coverartarchive.org/release/fa4f230a-e78c-32a8-bec8-3a7425aba9d2",
  "https://coverartarchive.org/release/fa023617-1585-4ae6-81b6-1a07c47ecb2a",
  "https://coverartarchive.org/release/61782e1c-67a2-487c-8324-6431c628cad8",
  "https://coverartarchive.org/release/b16e94f3-ad3b-4e3b-9fad-0ef3d2a0958e",
  "https://coverartarchive.org/release/37e7091f-9ebc-4ac8-875b-5c88f7e5fba8",
  "https://coverartarchive.org/release/a63b6cc9-899c-447d-b0e6-d1e439379eb2",
  "https://coverartarchive.org/release/d2d3df43-65c4-499e-90d2-22a157cc7dea",
  "https://coverartarchive.org/release/9cb95cac-4a0d-4fbb-9237-544a99f29b57",
  "https://coverartarchive.org/release/7cf87b52-47e3-4d12-8890-53a910792b70"
]

Usually, when a promise is resolved, it should return a JSON object, as seen when you enter one of those URLs provided above in your browser for album release cover art information. However, when trying to use Promise.all with this array, I am facing issues extracting the json() method. Despite attempting multiple methods found on stackoverflow or elsewhere online, I always encounter the error:

"Uncaught (in promise) TypeError: response.json is not a function"
Here are a few approaches I've tried:

  Promise.all(urlArray)
    .then(toJSON)
    .then((jsonObjects) => console.log(jsonObjects));

  function toJSON(responses) {
    if (!Array.isArray(responses)) {
      responses = [responses];
    }

    return Promise.all(responses.map((response) => response.json()));
  }

Similar approach without using a helper function:

    Promise.all(urlArray)
      .then((res) => {
        const responses = res.map((response) => response.json());
        return Promise.all(responses);
      })
      .then((data) => console.log(data));

The frustrating part is that I did manage to achieve this a few days ago but then changed my method and now can't remember how I initially solved it. If anyone has any insights on where I might be going wrong, feel free to point it out and scold me! Cheers.

Answer №1

Your urlArray contains plain strings and not requests. There are no network requests made in your code as there are no Promises present.

You need to first map the array of request URLs to an array of Promises.

const urlArray = [
  "https://coverartarchive.org/release/985adeec-a1fd-4e79-899d-10c54b6af299",
  "https://coverartarchive.org/release/4c54ee58-86df-3ba5-aaad-6b284293141b",
  "https://coverartarchive.org/release/cd8e5736-ec8c-3c4d-a231-ac097877d87a",
  // more URLs here
]
Promise.all(
  urlArray.map(
    url => fetch(url).then(res => res.json())
  )
)
  .then((results) => {
    console.log('got all results');
    // use results here
  });

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

Secure your website with the latest JWT cookie security measures

After storing a JWT with an expiry date set 30 days ahead, the question arises - is it secure to store this JWT in a cookie? The aim is for the token to persist beyond a single session, much like the "Keep me logged in" feature found on some websites. Se ...

Retrieving specific data from JSON by utilizing JSONPath, while omitting certain values

I have a JSON data set structured like this: [ { "accID": "3asdasd321asdasdfsadf2", "test": "one", "isGood": "true", }, { "accID": "Not Found", "test": "two", "isGood": "true", }, { "accID": "1asdasd121asdasdfsadf5", "test": "five", "isGood": "false", } ] ...

Enhanced jQuery implementation for hiding elements

I encountered a peculiar issue where jQuery's .is(':hidden') function wrongly returned true for an element that visibly displayed content. You can see the problem demonstrated in this fiddle. The :hidden pseudo checks both offsetWidth and o ...

Adding Data Definition Language (DDL) statements while making an AJAX call

Is there a way to automatically update the value of a drop-down list whenever a partial view is loaded via an AJAX call? Currently, the AJAX call successfully retrieves the necessary information, but the user still needs to manually change the location val ...

Display JSON array as a table using JavaScript

Looking for assistance with integrating an API that queries the Instagram API. I want to consume my API and display the Tags Search results in a table format. The JSON response structure is as follows: {"data":[{"media_count":13485788,"name":"argentina"}, ...

Utilizing jQuery boilerplate to execute functions

I am currently utilizing jQuery Boilerplate from However, I have encountered an issue where I am unable to call the "openOverlay" function within the "clickEvents" function. Oddly enough, I am able to successfully call "openOverlay" within the "init" fun ...

What is the best way to retrieve ember model relation properties within routes and controllers?

Currently using ember 2.7.0, I am facing an issue while setting up my ember app with a currentUser.organization derived from the authenticated token. Although I can successfully resolve the currentUser, I am encountering difficulties in resolving the prope ...

How can one smoothly rewind X frames in a video or animation on a webpage without experiencing lag?

For my thesis presentation, I decided to make it available online as a video with custom controls resembling a powerpoint slideshow. The challenge I encountered was with transitions between slides in an animated video. Certain transitions needed to loop fo ...

Utilizing Angular to Transform an Array of Dates

I have an array of dates which returns: [Mon Aug 03 2020 00:00:00 GMT+0100 (British Summer Time), Wed Aug 05 2020 00:00:00 GMT+0100 (British Summer Time)] I am looking to convert these into the following format: ["2020-02-13T02:39:51.054", &quo ...

Invoking a function within the directive's controller

How can I access and call the method defined within the directive controller externally? <div ng-controller="MyCtrl"> <map></map> <button ng-click="updateMap()">call updateMap()</button> </div> app.directive(&a ...

Experiencing difficulties accessing Facebook using ngFacebook on angularjs application

I've been working on implementing ngFacebook login into my Angular app, but I'm facing an issue with logging in to Facebook. Even after calling '$facebook.log()', nothing is being displayed in the console. This is a snippet of my Angul ...

Elements with v-for directive failing to display

I am attempting to incorporate a component using v-for. The data source infoTexts is structured as an Object where the locale code serves as the key and the corresponding message is the value. For example: { nl: 'Text in Dutch', fr: &apo ...

Utilizing Page Methods

I have encountered an issue while using an ajax callback for a void method. When I try to call another method within the calling method, I get an error. Any assistance with resolving this problem would be greatly appreciated. Here is the code snippet: ...

Modifying alignment of buttons in React components

Transforming the typical Tic Tac Toe game from the React tutorial, with an added one-player feature. Oddly, button alignment shifts out of place once a value is inserted; causing the button to drop by about 50px until the row is filled with values, after ...

Encountering a JavaScript Error: "e is null" while utilizing assert for checking JavaScript alert text

I encountered a javascript alert in my program that I was able to interact with by reading the text and clicking on the buttons. However, when I tried to verify the alert text using assertequals function, I faced an error. Here is the code snippet: String ...

Using JQuery to reveal a hidden child element within a parent element

I'm facing a challenge with displaying nested ul lists on my website. The parent ul is hidden with CSS, causing the child ul to also remain hidden even when I try to display it using jQuery. One approach I've attempted is adding a class to the f ...

The issue with Infinite Scrolling/Pagination feature in backbone.js persists

My goal is to implement an infinite scroll feature similar to Twitter using the Pagination plugin for backbone.js. Clicking the button/link #pagination a should load the next page of results from the backend and append it to the current view PhotoListView. ...

"Using regular expressions in a MongoDB find() query does not provide the desired

app.get("/expenses/:month", async (req, res) => { const { month } = req.params; const regexp = new RegExp("\d\d\d\d-" + month + "-\d\d"); console.log(regexp); const allExpenses ...

issue with useReducer not functioning as expected

I encountered an issue with my customized Select component. It includes a select and options while listening for onChange events. Additionally, I am using a useReducer function that initializes some variables. However, even after selecting an option, the s ...

What is the correct method for redefining properties and functions in Vue.js?

Is there a proper method for overriding methods using mixins in Vue.js? While it's possible to mimic inheritance with mixins, what if you only want to extend certain props without completely replacing the entire prop value? For example, let's sa ...