【发布时间】:2020-07-09 16:11:02
【问题描述】:
下面是一个 sn-p,它通过多次请求检索前 N 页数据,在 HackerNews api 中搜索关键字“java”
理想情况下,它应该检索数据集的前 3 页:
https://hn.algolia.com/api/v1/search_by_date?query=java&page=0
https://hn.algolia.com/api/v1/search_by_date?query=java&page=1
https://hn.algolia.com/api/v1/search_by_date?query=java&page=2
这里是代码,also available as a CodePen
// Fetch all HackerNews posts with the search string 'java'
const url = 'https://hn.algolia.com/api/v1/search_by_date';
const config = {
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
params: { query: 'java', page: null }
};
const numPagesToFetch = 3;
// Build a series of requests, one for each page
let requests = [];
for (var i = 0; i < numPagesToFetch; i++) {
// Duplicate the `config` object for each request
let requestCfg = Object.assign({}, config);
// The only `param` changing for each request is `?page=`
// HN API starts numbering from page 0
requestCfg.params.page = i;
console.log(`Generating request for page ${requestCfg.params.page}`);
requests.push(axios.get(url, requestCfg));
}
// Wait on all requests to complete in parallel, then handle the output
Promise.all(requests).
then((responses) => {
// Should be equal to numPagesToFetch (3)
console.log(`Number of responses: ${responses.length}`);
for(var i = 0; i < responses.length; i++) {
// Print out some info about each response
const firstId = responses[i].data.hits[0].story_id;
const requestUrl = responses[i].request.responseURL;
console.log(`Dataset Response from ${requestUrl} starts with id ${firstId}`);
}
}).
catch(error => {
console.log('There was an error');
})
当我运行它时,它似乎多次检索同一页面(最后一页)
https://hn.algolia.com/api/v1/search_by_date?query=java&page=2
https://hn.algolia.com/api/v1/search_by_date?query=java&page=2
https://hn.algolia.com/api/v1/search_by_date?query=java&page=2
我觉得这与 JS 或 axios 如何处理对变量的引用有关。当我构建每个请求并增加page 时,它会影响使用相同变量构造的所有其他请求。我什至注意“复制”config 对象,但它没有帮助。
知道为什么它会发出 3 次相同的请求吗?
谢谢!
【问题讨论】:
标签: javascript object get axios