fro*_*ace 0 javascript recursion node.js async-await
鉴于此异步递归函数(如果您在安装了 axios 的情况下复制并粘贴它,则在节点上工作):
const axios = require('axios');
fetchAllSync('https://api.github.com/repos/octokit/rest.js/issues/comments', {per_page:100})
.then(function(data){
console.log(data.length);
});
async function fetchAllSync(requestUrl, parameters) {
// Construct request url with given parameters
requestUrl = parameters ? `${requestUrl}?`: requestUrl;
for(let parameter in parameters){
requestUrl = requestUrl.concat(`${parameter}=${parameters[parameter]}&`);
}
let res = await axios.get(requestUrl);
// Return results immediataly if there is only 1 page of results.
if(!res.headers.link){
return Promise.resolve(res.data);
}
// Get page relation links from header of response and make request for next page of comments
let linkRelations = res.headers.link.split(',').map(function(item) {
return item.trim();
});
for(let linkRel of linkRelations){
let [link, rel] = linkRel.split(';').map(function(item) {
return item.trim();
});
link = link.substring(1, link.length - 1);
if(rel == 'rel="next"'){
// Make recursive call to same method to get next page of comments
return res.data.concat(await fetchAllSync(link));
}
}
return res.data;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码有效。它使用标头中的链接关系获取下一页数据的请求 url,并使用递归检索一组新数据。
但是,如果我更改async function fetchAllSync(requestUrl, parameters)为async function fetchAllSync(requestUrl, parameters={})我的代码会中断。发生的情况是第一页数据被正确检索,但随后的递归调用一遍又一遍地检索相同的数据。
当我 console.log 的 requestUrl 参数时,它确实是第二页数据的 url。对于所有后续调用,它也是相同的 requestUrl。为什么会这样?即使来自 axios 调用的响应也说请求了第二页,那么当我给 一个默认值时,为什么标题中的链接关系没有反映这一点parameter?
这可能是由于requestUrl = parameters ? `${requestUrl}?`: requestUrl;线路
const alice = undefined ? 'foo' : 'bar'
const bob = {} ? 'foo' : 'bar
console.log(alice); // 'bar'
console.log(bob); // 'foo'
Run Code Online (Sandbox Code Playgroud)
这是因为Boolean({})返回 true,并且?操作符会发生隐式强制转换
| 归档时间: |
|
| 查看次数: |
144 次 |
| 最近记录: |