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

Tim*_*ehn 6 javascript fetch

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

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);
  }
Run Code Online (Sandbox Code Playgroud)

它控制台.logs 0而不是3,因为它不等待所有的承诺得到解决.我怎样才能使它成为console.log 3?如果您知道解决方案,请帮帮我.

Jos*_*osh 9

在所有承诺完成之前您不能调用 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);
  });
  }
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢你的想法。它确实有效,但前提是所有提取请求都成功解决了……如果其中一个提取请求失败,您知道我如何获得 console.log 吗? (2认同)

ama*_*ksr 6

您可以将 async/await 与 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')});
Run Code Online (Sandbox Code Playgroud)


amr*_*ngh 0

您可以尝试链接您的承诺,尝试以下操作:

function getPosts(){

  let url = ["https://www.freecodecamp.org", "https://www.test.de/, http://www.test2.com"];
  let array = new Array;
  var promise = Promise.resolve();
  for (let i = 0; i < url.length; i++) {
    console.log(url[i]);
    promise = promise.then(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.then(function(response){
    console.log (array.length);
  });
}
Run Code Online (Sandbox Code Playgroud)