我试图形成一个url数组,然后执行并行获取使用。map和Promise.all如果我尝试用手动制作的数组,但如果我试图用for循环形成一个数组(用于分页),则代码本身不起作用。我从第一次读取的报头中获得最大页数,并使用for循环添加页数递增的页面,直到最终的页数。
我意识到试图在这里做一个最低限度可复制的例子,这不是'工作'在某种意义上,当我这样做在我的服务器与这个示例代码,它的工作和
console.log(urls);
实际上显示了循环的url,它似乎是在数组格式,因为我用推似乎不可能?但在执行url时。映射它根本不起作用,尝试做其他事情,比如。slice到url它也不起作用,所以我感觉到我没有形成我认为的数组?我想不明白。
async function smt() {
var url = 'https://jsonplaceholder.typicode.com/todos/';
var urls = [];
var firstFetch = fetch(url)
.then(function(e) {
var maxpages = 5;
//var maxpages = e.get.headers('TotalPages'); < I would get the maxpages here
for (let i = 1; i < maxpages; i++) {
urls.push(url + i)
}
});
console.log(urls);
var data = await Promise.all(urls.map(async url => {
const res = await fetch(url);
return res.json();
}))
console.log(data);
var other = [
'https://jsonplaceholder.typicode.com/todos/1',
'https://jsonplaceholder.typicode.com/todos/2',
'https://jsonplaceholder.typicode.com/todos/3',
'https://jsonplaceholder.typicode.com/todos/4',
]
var data2 = await Promise.all(other.map(async url => {
const res = await fetch(url);
return res.json();
}))
console.log(data2);
}
smt();
问题是与。then()函数我没有线索,但我测试了每个部分,直到它工作。
async function smt() {
var url = 'https://jsonplaceholder.typicode.com/todos/';
var urls = [];
var firstFetch = await fetch(url)
var maxpages = 5;
//var maxpages = firstFetch.get.headers('TotalPages'); < I would get the maxpages here
for (let i = 1; i < maxpages; i++) {
urls.push(url + i)
}
console.log(urls);
var data = await Promise.all(urls.map(async url => {
const res = await fetch(url);
return res.json();
}))
console.log(data);
var other = [
'https://jsonplaceholder.typicode.com/todos/1',
'https://jsonplaceholder.typicode.com/todos/2',
'https://jsonplaceholder.typicode.com/todos/3',
'https://jsonplaceholder.typicode.com/todos/4',
]
var data2 = await Promise.all(other.map(async url => {
const res = await fetch(url);
return res.json();
}))
console.log(data2);
}
smt();
/****更新答案****/
async function smt() {
var url = 'https://jsonplaceholder.typicode.com/todos/';
var urls = [];
//var firstFetch = await fetch(url) < would get headers
var maxpages = 5;
//var maxpages = firstFetch.get.headers('TotalPages'); < I would get the maxpages here
for (let i = 1; i < maxpages; i++) {
urls.push(url + i)
}
console.log(urls);
let promises = urls.map(async url => {
let a = await fetch(url);
return a.json()
})
var data = await Promise.all(promises)
console.log(data);
}
smt();
我认为这是一个更好的方法,因为你可以限制并发当你做url。
我已经在节点中使用了p-limit,它工作得很好。
const limit = pLimit(8);
let promises = urls.map(url => {
return limit(async() => {
let a = await fetch(url, optionsGet)
return a.json()
})
});