What is the best way to retrieve data from an array of promises when utilizing promise.all in JavaScript?

I'm struggling to retrieve information from the restcountries.eu API using a promise.all method, and I am having difficulty identifying the issue.

function displayCurrency(currencyone, currencytwo) {
    
    Promise.all([
        fetch(`https://restcountries.eu/rest/v2/currency/${currencyone}`),
        fetch(`https://restcountries.eu/rest/v2/currency/${currencytwo}`)
    ])
        .then(function (responses) {
            return responses.map(function (response) {
                return response.json();
            });
        }).then(function (data) {
          
            console.log(data[0]);


        }).catch(function (error) {
            console.log(error);
        });

}

data[0] returns a resolved promise containing an array. Despite my attempts to access data within the array like 'name' and 'currencies', all I receive is undefined values.

Answer №1

When you're mapping after the initial fetch, you end up creating an array of .json() calls that are essentially Promises. To handle this, you must once again apply Promise.all.

// This code snippet is not executable and hidden by default;
// Using a more elegant approach is recommended

function displayCurrency(currencyone, currencytwo) {
    const arrOfJsonProms = Promise.all([
        fetch(`https://restcountries.eu/rest/v2/currency/${currencyone}`),
        fetch(`https://restcountries.eu/rest/v2/currency/${currencytwo}`)
    ])
        .then(function (responses) {
            return responses.map(function (response) {
                return response.json();
            })
        });
    Promise.all(arrOfJsonProms)
        .then(function (data) {
            console.log(data[0]);
        }).catch(function (error) {
            console.log(error);
        });
}

Alternatively, a cleaner solution would be to call .json directly within the initial Promise.all, making the code simpler while avoiding the need to wait for all connections to initialize before downloading data:

function displayCurrency(currencyone, currencytwo) {
    Promise.all([
        fetch(`https://restcountries.eu/rest/v2/currency/${currencyone}`).then(res => res.json()),
        fetch(`https://restcountries.eu/rest/v2/currency/${currencytwo}`).then(res => res.json())
    ])
        .then(function (data) {
            console.log(data[0]);
        }).catch(function (error) {
            console.log(error);
        });
}

Answer №2

If you're looking to harness the power of async/await, you can do so with the following approach:

const fetchCurrencyData = async (currencyCode1, currencyCode2) => {
  try {
    let responses = await Promise.all([
      fetch(`https://restcountries.eu/rest/v2/currency/${currencyCode1}`),
      fetch(`https://restcountries.eu/rest/v2/currency/${currencyCode2}`),
    ]);
    let data = await Promise.all(
      responses.map(async (response) => await response.json())
    );
    console.log(data[0]);
  } catch (error) {
    console.log(error);
  }
};

fetchCurrencyData("eur", "aud");

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

Issue with Submit Event in React - Enter Key Fails to Trigger

I'm currently experimenting with a small front-end react project that's using Soundcloud's API. The project is quite basic at the moment - it takes user input and queries the API for related songs. I've encountered an issue where the en ...

Having trouble deciphering this snippet of Express JS source code

Upon reviewing the Express JS source code, I came across the main module where express is being exported. module.exports = createApplication; function createApplication() { var app = function(req, res, next) { app.handle(req, res, next); }; m ...

Different types of forms displayed together with a sole submission button in a separate section

https://i.sstatic.net/aAbD9.jpg My webpage consists of two main sections: the red section which is a partial view containing actions for forms, and the blue section which contains tabbed forms. Each tab in the blue section is also a view, called using the ...

Experiencing a hiccup in your jQuery animation?

Click here to access the fiddle demonstrating the issue. A situation arises where a span with display: inline-block houses another span that is being slowly hidden. The container span unexpectedly shifts back to its original position once the hiding proces ...

The error message "TypeError: language.map is not a function" occurred while attempting to retrieve data with

I have created a component using MUI for tables. I am fetching data from an API and then using the map method to display the data. However, I encountered an error message that reads: TypeError: language.map is not a function When I try putting "language" ...

"What could be the reason for web3.eth.getAccounts() method returning an empty array when used with console.log

Upon executing web3.eth.getAccounts().then(console.log);, I encountered an empty array and also received a warning stating ./node_modules/web3-eth-accounts/src/scrypt.js Critical dependency: the request of a dependency is an expression. The project began w ...

Tips for utilizing AJAX in Angular to load web pages in partials

My goal is to display a loader for each container while making an AJAX call to retrieve content. Initially, I want both div columns to show the loader, and then once the AJAX call is successful, I need to hide the loader for that specific column. Despite ...

How to efficiently retrieve a form's data from multiple forms with identical ids in JavaScript

I am facing a challenge with multiple forms on the html page that have the same ID. I need to send each form's information to the server based on user selection, but I haven't been able to find a relevant solution. For my Authorization polic ...

Every Dynamic Post automatically defaults to the initial object

I am currently developing an app that retrieves feeds from a Wordpress site and displays individual posts in a jQuery mobile list format. Here is the JavaScript code I am using: $(document).ready(function () { var url = 'http://howtodeployit.com/ ...

Modifying the parent directive's DOM in response to an event triggered by the child directive

I need help figuring out how to implement a custom radio-buttons list directive in the correct way. Imagine I want to create a directive like this: <my-radio-button-list> <my-radio-button> ...Some HTML content... </my-radio ...

Ways to convert all keys to uppercase in an array of objects?

Is there a way to capitalize the first letter of every key in an array of objects? I attempted to achieve this with the code below, but it's not working as expected. Any suggestions or corrections are appreciated. #current code function capitalizeO ...

Struggling to display Firestore data in a React component - useRef() does not trigger re-render and useState() throws an error

I am currently working on a project involving a React component called Dashboard. The component includes various features such as loading data from a Firestore database and displaying it on the page. While implementing this functionality, I encountered an ...

Refining a collection of deeply nested objects

Currently, I am attempting to create a filter pipe in Angular2 that will be able to sift through an array containing various nested objects. These objects are retrieved from Salesforce and sometimes include nested objects as shown below: Object { Id: ...

Is it possible to import the headers from a CSV file into a table for the purpose of comparing them to the existing headers in the system?

I'm currently working on loading two CSV files - one is the default for our system, while the other is the file we want to import. My goal is to create a table displaying the default content on one side and providing a dropdown list for selecting colu ...

Creating dropdown menus dynamically and populating them based on the selection made in one dropdown menu to determine the options available

Looking to enhance the filtering options in my ngGrid, I stumbled upon the concept of Filtering in Ignite UI grid and was impressed by its functionality. I am now attempting to implement a similar feature in AngularJS. Breaking down the task into 4 compon ...

What is the best way to add a bottom border to each row in a textarea?

I am currently exploring methods to include a border-bottom line for each row in a <textarea>, but so far I have only been able to achieve this on the very bottom row. Is there any way to make this happen? .input-borderless { width: 80%; bord ...

JavaScript and JSON interchangeably, the first AJAX response should be rewritten by the second response

I am facing an issue with my code: I have two ajax calls being made on window.load, and it seems like the response from the second AJAX call is overwriting the response from the first one before my function can process it. I'm not sure where I'm ...

Ways to activate a special function after clicking a social media button?

My goal is to implement a social media div locker on my website. The concept involves hiding a piece of text behind a div locker that prompts the user to share the content on Facebook, Google+, or Twitter in order to unlock it. After the visitor clicks on ...

An issue has occurred: Unable to access information of unknown origin (reading 'admin')

Hey there, I am encountering an issue when attempting to restructure my project as MVC. I am implementing use cases in my models with the goal of organizing my structure like this: When a route is accessed, it goes to the controller and then the controller ...

Two Elements Linked Together

I'm facing an issue with my interconnected React components. Despite being separate entities, they appear to share some styling attributes which I find puzzling. The main problem lies in the footer component as it seems linked to another component, p ...