多个fetch api调用如何检查所有调用是否已完成?

Muh*_*mer 11 javascript html5 asynchronous promise ecmascript-6

我从多个网址抓取内容.Fetch api全面使用promises.

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

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

现在我有一系列的网址和多个电话将如何知道所有电话是否已经完成.

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

Yur*_*nko 20

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

// 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`))
Run Code Online (Sandbox Code Playgroud)

  • @clurect - 这还不够.`Promise.all()`接受一系列的承诺.如果你只是传递一个URL数组,它将不会做任何有用的事情. (5认同)