[英]Correctly duplicating a JS object when building multiple GET requests (with Axios)
Below is a snippet that searches HackerNews api for the keyword 'java' by making multiple requests to retrieve the first N pages of data下面是一个片段,它通过多次请求检索前 N 页数据,在 HackerNews api 中搜索关键字“java”
Ideally it should retrieve the first 3 pages of the data set:理想情况下,它应该检索数据集的前 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
Here is code, which is also available as a CodePen这是代码,也可用作 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');
})
When I run this, it seems to be retrieving the same page (the last page) multiple times当我运行它时,它似乎多次检索同一页面(最后一页)
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
I feel like it has something to do with how JS or axios handles references to variables.我觉得这与 JS 或 axios 如何处理对变量的引用有关。 As I build each request and increment the page
, it's impacting all the other requests constructed with that same variable.当我构建每个请求并增加page
时,它会影响使用相同变量构造的所有其他请求。 I even took care to "duplicate" the config
object, but it doesn't help.我什至注意“复制” config
object,但这没有帮助。
Any idea why it's making the same request 3 times?知道为什么它会发出 3 次相同的请求吗?
Thanks!谢谢!
This is because you are not cloning it deeply, you only clone the root object but the inner objects still point to their original object...you can either use https://www.npmjs.com/package/clone-deep or use this little trick of converting it to a string then parsing as object:这是因为您没有深度克隆它,您只克隆了根 object 但内部对象仍然指向它们原来的 object ...您可以使用https-://www.npmone或使用 js.这个将其转换为字符串然后解析为 object 的小技巧:
let requestCfg = JSON.parse(JSON.stringify(config));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.