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

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

问题描述

我有这个问题:我想在一个for循环中进行多个提取调用.呼叫次数取决于用户输入(在我的示例中,我有3个).我如何才能使其遍历所有提取请求,然后在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?

function 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,因为它不等待所有的诺言得到解决.我如何使其进入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.

推荐答案

您可以对try/catch使用async/await:

You can use async/await with try/catch:

async function getPosts(){
  let array = [];
  let url = ["https://www.freecodecamp.org", "https://www.test.de/", "http://www.test2.com"];
  let reg = /\<meta name="description" content\=\"(.+?)\"/;
  for (let i = 0; i < url.length; i++)   {
    console.log('fetching',url[i]);
    try {
      let p1 = await fetch(url[i]);
      let p2 = await p1.text();
      let res = p2.match(reg);
      array.push(res);
      console.log('adding',res);
    }
    catch (e) {
      console.error(e.message);
    }
  };
  console.log ('length',array.length);
};

getPosts().then(()=>{console.log('done')});

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

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