Как получить доступ к данным выборки из массива обещаний при использовании обещания в Javascript - PullRequest
0 голосов
/ 10 апреля 2020

Я пытаюсь получить доступ к данным из API restcountries.eu с помощью promise.all, но не могу понять, что я делаю неправильно.

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] отображает разрешено обещание с массивом. Я пытаюсь получить доступ к данным в массиве, таким как «имя» и «валюта», но я просто получаю неопределенный.

Ответы [ 2 ]

0 голосов
/ 10 апреля 2020

Вы также можете использовать async/await, что-то вроде следующего:

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

displayCurrency("eur", "aud");
0 голосов
/ 10 апреля 2020

После сопоставления вы создаете массив .json() вызовов - массив Обещаний. Вам нужно будет снова позвонить Promise.all.

// Not actually runnable, just hidden by default;
// this is very inelegant, use the other method instead

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);
        });
}

Но было бы более элегантно вызвать .json внутри начального Promise.all, так что код проще и , а вы этого не сделаете перед загрузкой тела нужно дождаться инициализации каждого соединения:

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);
        });
}
...