【问题标题】:Converting from Axios to Fetch with Promise.all()使用 Promise.all() 从 Axios 转换为 Fetch
【发布时间】:2016-09-02 03:19:01
【问题描述】:

我正在使用Promise.all() 进行一堆axios.get() 调用,并确保它们在继续之前都返回,如下所示:

Promise.all([getJSON1(), getJSON2()])
    .then((arr) => {
        var data = {
            json1: arr[0],
            json2: arr[1]
        };

        return data;
    });

函数getJSON1()getJSON2() 看起来像:

function getJSON1() {
    return axios.get('json1-url.json');
}

这一切都很好,但是我想知道当 webpack 完成它的工作时,用 fetch 替换 axios 是否会减小我最终 bundle.js 的大小。

我正在尝试fetch polyfill 并根据this blog 将其与webpack 集成,但是我只是不确定如何调整getJSON1() 以使用fetch。我尝试了以下方法:

function getJSON1() {
    return fetch('json1-url.json');
}

这会导致 TypeError: Object is not a constructor (evalating 'new Promise')

【问题讨论】:

  • 您是否单独测试了每个 fetch 调用?例如getJSON1()getJSON2() 自己工作好吗?错误指向您的代码中的哪个位置?

标签: webpack es6-promise polyfills fetch-api axios


【解决方案1】:

我们可以这样调用fetch方法,希望对你有帮助:-

function getJSON1() {
    return fetch('json1-url.json')
      .then((response) => response.json())
      .then((responseJson) => {
        return responseJson;

      })
      .catch((error) => {
        console.error(error);
      });
}

【讨论】:

    猜你喜欢
    • 2019-06-24
    • 1970-01-01
    • 2022-01-15
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 2021-08-17
    • 1970-01-01
    相关资源
    最近更新 更多