【问题标题】:Making multiple fetch api calls how to check if all calls have finished? [duplicate]进行多个 fetch api 调用如何检查所有调用是否已完成? [复制]
【发布时间】:2016-11-04 04:24:02
【问题描述】:

我正在从多个网址抓取内容。 Fetch api 到处使用 Promise。

所以我的一个请求的代码看起来像这样

fetch(url).then((response)=>response.text()).then(function(html) { //stuff });

现在我有一组 url,并且将进行多次调用我如何知道是否所有调用都已完成。

我尝试使用Promise.all,但如果您看到每个请求都有两个承诺。有没有更好的方法,Promise.all 的支持也不是很好。

【问题讨论】:

  • Promise.all 在这里可以正常工作,只要您链接请求。在任何支持fetch 的地方,Promise 也将支持。
  • 好的,如果你有一组 url,你能举个例子吗?你将如何使用 promise.all
  • Promise.all(urls.map(url => fetch(url).then(res => res.text()).then(html => (/* stuff */))).then(() => console.log('all urls were fetched and processed'))
  • 感谢@YuryTarabanko,如果您提出答案,请接受它

标签: javascript html asynchronous promise ecmascript-6


【解决方案1】:

假设您有一个名为 urls 的 url 数组

// separate function to make code more clear
const grabContent = url => fetch(url)
     .then(res => res.text())
     .then(html => (/* process html here */))

Promise
    .all(urls.map(grabContent))
    .then(() => console.log(`Urls ${urls} were grabbed`))

【讨论】:

  • Promise.all([url1,url2]).then() 也可以
  • @clurect - 这还不够。 Promise.all() 接受一系列承诺。如果你只是传递一个 URL 数组,它不会做任何有用的事情。
  • @clurect urls 是一个字符串数组(来自 OP:现在我有一个 url 数组)。用 Promise 包装它没有多大意义。
  • 啊,是的,我的错。应该是承诺。
猜你喜欢
  • 1970-01-01
  • 2018-09-23
  • 1970-01-01
  • 2015-01-19
  • 2011-10-18
  • 2013-07-23
  • 2021-07-02
  • 2021-01-07
  • 1970-01-01
相关资源
最近更新 更多