如何在 for 循环中使用 fetch,等待结果,然后 console.log 它 [英] How to use fetch within a for-loop, wait for results and then console.log it

查看:44
本文介绍了如何在 for 循环中使用 fetch,等待结果,然后 console.log 它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题:我想在一个 for 循环中进行多次 fetch 调用.调用次数取决于用户输入(在我的示例中,我有三个).我怎样才能让它遍历所有的 fetch 请求,然后 console.log 关闭电话号码?

i have this problem: i want to make multiple fetch calls within a for-loop. The number of calls depend on the user input (in my example i have three). How can i make it loop through all the fetch requests and then console.log the number off calls?

函数 getPosts(){

function getPosts(){

  let url = ["https://www.freecodecamp.org", "https://www.test.de/, http://www.test2.com"];
  let array = new Array;

  for (let i = 0; i < url.length; i++) {
    console.log(url[i]);
    fetch(url[i])
    .then(res => {return res.text(); })
    .then(res => {
            let reg = /<meta name="description" content="(.+?)"/;
            res = res.match(reg);
            array.push(res);
            console.log(res);
          }
    )
    .catch(status, err => {return console.log(status, err);})
  }
  console.log (array.length);
  }

它 console.logs 是 0 而不是 3,因为它不会等待所有的 Promise 都被解决.我怎样才能使它成为console.log 3?如果您知道解决方案,请帮助我.

It console.logs 0 instead of 3, cause it doesn't wait for all the promises to be resolved. How can i make it to console.log 3? If you know a solution, please help me out.

推荐答案

你不能调用console.log(array.length),直到之后所有的promise都完成了.那么为什么不这样呢?

You can't call console.log(array.length) until after the promises are all done. So why not something like this?

let url = ["https://www.freecodecamp.org", "https://www.test.de/, http://www.test2.com"];
  let array = new Array;
  var fetches = [];
  for (let i = 0; i < url.length; i++) {
    console.log(url[i]);
    fetches.push(
      fetch(url[i])
      .then(res => {return res.text(); })
      .then(res => {
            let reg = /<meta name="description" content="(.+?)"/;
            res = res.match(reg);
            array.push(res);
            console.log(res);
          }
      )
      .catch(status, err => {return console.log(status, err);})
    );
  }
  Promise.all(fetches).then(function() {
    console.log (array.length);
  });
  }

Promise.all 等待所有提取完成,然后它会打印 #.

Promise.all waits for all the fetches to finish, THEN it'll print the #.

这篇关于如何在 for 循环中使用 fetch,等待结果,然后 console.log 它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆