如何在 for 循环中使用 fetch,等待结果然后 console.log

新手上路,请多包涵

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

函数 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?如果您知道解决方案,请帮助我。

原文由 Timo Hoehn 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
1 个回答

承诺全部完成之前,您不能调用 console.log(array.length) 。那么为什么不是这样的呢?

 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 等待所有提取完成,然后它会打印#。

原文由 Josh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题