【问题标题】:How do I access fetch data from an array of promises when using promise.all in Javascript在 Javascript 中使用 promise.all 时如何从一组 promise 中获取数据
【发布时间】:2020-04-10 14:06:40
【问题描述】:

我正在尝试使用 promise.all 从 restcountries.eu API 访问数据,但我不知道我做错了什么。

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] 显示带有数组的已解决承诺。我尝试访问数组中的数据,例如“名称”和“货币”,但我一直未定义。

【问题讨论】:

    标签: javascript api fetch fetch-api


    【解决方案1】:

    映射后,您将创建一个 .json() 调用数组 - 一个 Promises 数组。您需要再次致电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);
            });
    }

    但是在初始的Promise.all 中调用.json 会更优雅,这样代码会更简单并且您不必在下载之前等待每个连接都初始化正文:

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

    【讨论】:

      【解决方案2】:

      您也可以使用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");

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-27
        • 1970-01-01
        • 2015-10-21
        • 1970-01-01
        相关资源
        最近更新 更多