【问题标题】:How to wait for multiple fetches to complete in JavaScript?如何在 JavaScript 中等待多个提取完成?
【发布时间】:2021-03-15 18:37:01
【问题描述】:

我需要等待两次fetch() API 调用,然后将每次获取的数据保存到不同的窗口对象。我找到了这篇文章https://gomakethings.com/waiting-for-multiple-all-api-responses-to-complete-with-the-vanilla-js-promise.all-method/ 并尝试了以下代码来等待 API 调用:

Promise.all([
    fetch('https://jsonplaceholder.typicode.com/todos/1'),
    fetch('https://jsonplaceholder.typicode.com/todos/2')
]).then(function (responses) {
    // Get a JSON object from each of the responses
    return Promise.all(responses.map(function (response) {
        return response.json();
    }));
}).then(function (data) {
    // Log the data to the console
    // You would do something with both sets of data here
    console.log(data);
}).catch(function (error) {
    // if there's an error, log it
    console.log(error);
});

但是,在浏览器控制台中粘贴时,结果不会被记录。

代码有什么问题以及如何等待两者都解决?

【问题讨论】:

  • 如果任何请求失败怎么办?
  • 你说的是哪个回报?
  • 看起来不错,您将在console.log(data);获得最终数据
  • 您的代码看起来很好,并且在两个承诺都解决后打印数据。不确定你说的问题
  • 在控制台中粘贴代码时,不会记录结果@VinuPrasad

标签: javascript asynchronous


【解决方案1】:

你可以试试这个东西。我在小提琴上对其进行了测试,看起来它可以工作。

Promise.all([
  fetch("https://jsonplaceholder.typicode.com/todos/1"),
  fetch("https://jsonplaceholder.typicode.com/todos/2")
]).then(responses =>
  Promise.all(responses.map(response => response.json()))
).then(data =>
  console.log(data)
).catch(err =>
  console.log(err)
);

【讨论】:

    【解决方案2】:

    const fetchData = async () => {
      try {
        const [respTodoOne, respTodoTwo] = await Promise.all([
            fetch('https://jsonplaceholder.typicode.com/todos/1'),
            fetch('https://jsonplaceholder.typicode.com/todos/2')
        ]);
        const todoOne = await respTodoOne.json();
        const todoTwo = await respTodoTwo.json();
        console.log(todoOne, 'todoOne');
        console.log(todoTwo, 'todoTwo');
      } catch (err) {
        throw err;
      }
    };
    
    fetchData();

    可能正在寻找类似的东西。

    【讨论】:

      【解决方案3】:

      问题在我这边。我不小心过滤了浏览器控制台。不过谢谢大家的帮助。

      【讨论】:

        【解决方案4】:

        我的建议:

        let url = "https://jsonplaceholder.typicode.com/todos/";
        
        async function doRequest() {
          let toDo1 = await (await fetch(url + "1")).json();
          console.log(toDo1);
          let toDo2 = await (await fetch(url + "2")).json();
          console.log(toDo2);
        }
        
        doRequest()
          .catch(err => console.log(err));

        这样,如果需要获取多个项目,可以在函数内部使用循环。

        【讨论】:

          【解决方案5】:

          请使用 axios 获取 js 中的数据。反应或角度等......

          https://github.com/axios/axios 请使用 npm 安装并阅读文档

          $ npm install axios
          
          axios.get('/user')
            .then(function (response) {
              console.log(response);
              axios.get('/user')  .then(function (res) {
               console.log(res);
              })
            })
          

          当第一个请求完成时, 然后开始请求秒

          【讨论】:

          • 你为什么推荐一个库而不是找出实际问题?
          • 因为解决方案变得更容易。这个图书馆为我们提供了更好的设施
          猜你喜欢
          • 1970-01-01
          • 2018-02-24
          • 1970-01-01
          • 1970-01-01
          • 2022-01-15
          • 2010-11-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多