【发布时间】:2018-02-02 17:20:44
【问题描述】:
我正在使用 github API 来遍历 repo 并获取其中所有文件的列表。这种结构称为“树”。树基本上是一个子目录。因此,如果我想查看一棵树的内容,我需要对该树的 ID 发出 GET 请求。响应将是表示该树中项目的对象数组。但是其中一些项目也将是树,所以我必须向该树发出另一个获取请求。一个 repo 可能如下所示:
|src
app.jsx
container.jsx
|client
index.html
readme.md
此结构将由以下对象表示
[
{ name:'src', type:'tree', id:43433432 },
{ name:'readme.md', type:'md', id:45489898 }
]
//a GET req to the id of the first object would return the following array:
[
{ name:'app.jsx', type:'file', id:57473738 },
{ name:'contain.jsx', type:'file', id:748433454 },
{ name:'client', type:'tree', id:87654433 }
]
//a GET req to the id of the third object would return the following array:
[
{ name:'index.html', type:'file', id:44444422 }
]
我需要做的是编写一个函数,该函数将返回一个包含所有文件名称的数组。这变得非常棘手,因为我正在尝试将异步调用与递归结合起来。这是我迄今为止的尝试:
function treeRecurse(tree) {
let promArr = [];
function helper(tree) {
tree.forEach(file => {
let prom = new Promise((resolve, reject) => {
if (file.type == `tree`) {
let uri = treeTrunk + file.sha + `?access_token=${config.ACCESS_TOKEN}`;
request({ uri, method: 'GET' })
.then(res => {
let newTree = JSON.parse(res.body).tree;
resolve(helper(newTree));
});
} else resolve(promArr.push(file.path));
promArr.push(prom);
});
});
};
helper(tree);
Promise.all(promArr)
.then(resArr => console.log(`treeRecurse - resArr:`, resArr));
};
它正在遍历所有内容,但 promArr 解决得太快了。另外,我不确定要解决什么问题。拦住我。
【问题讨论】:
-
你的意思是
//a GET req to the id of the **third** object would return the following array:... -> ...[ { name:'index.html', type:'file', id:44444422 } ]? -
@redu yes ty 已编辑
标签: javascript node.js github promise github-api