这样做的目的是在继续之前对请求进行几次循环。在我可以继续并使用结果之前,github.repos.getBranch应该构建一个包含10个元素的对象。
github api请求按预期工作,但结果记录在:console.log('++', res)上,返回的结果如下:++ [ undefined, undefined, undefined, undefined, undefined ]。如果我在循环结束后记录allBranches,数据都在那里。
在github请求之后,我显然遗漏了一个步骤。我已经用我能想到的所有方法对其进行了重构,但都没有成功。
getAllData: () => {
let allBranches = []
let startGetData = config.repositories.map(repo => {
config.branches.map(branch => {
return allBranches.push(
github.repos.getBranch({
owner: config.organisation,
repo,
branch
})
)
})
})
return Promise.all(startGetData)
.then(res => {
console.log('++', res)
})
}发布于 2017-07-29 16:43:30
您没有从config.repositories.map调用中返回任何内容(这是一个没有return的冗长箭头函数)。所以你最终得到了一个undefined数组,这是你传递给Promise.all的,你需要一个return。
但这并不是唯一的问题。您正在将startGetData传递给Promise.all,但github承诺的内容并不存储在那里。您将它们存储在allBranches中。所以你需要等待allBranches,而不是startGetData。
我怀疑您的目标是获得一个包含分支数组的存储库数组。如果是这样,您将需要多个Promise.all调用(在存储库的分支上等待)和一个总体Promise.all调用(等待所有存储库完成)。
如果这就是你的目标,这里有一种方法:
getAllData: () => Promise.all( // Gather up all results
config.repositories.map(repo => // Map repos to promises
Promise.all(config.branches.map(branch => // Map branches to promises
github.repos.getBranch({ // Promise for branch
owner: config.organisation,
repo,
branch
})
)).then(branches => ({repo, branches})) // Wrap up branch results in...
) // ...an object identifying...
) // ...the repo这为您提供了这样一个对象数组的承诺:
[
{
repo: /*...repo...*/,
branches: [
/*...branch...*/,
/*...branch...*/,
/*...branch...*/
]
},
{
repo: /*...repo...*/,
branches: [
/*...branch...*/,
/*...branch...*/,
/*...branch...*/
]
},
{
repo: /*...repo...*/,
branches: [
/*...branch...*/,
/*...branch...*/,
/*...branch...*/
]
}
]如果您只想要一个纯数组的数组:
[
[
/*...branch...*/,
/*...branch...*/,
/*...branch...*/
]
[
/*...branch...*/,
/*...branch...*/,
/*...branch...*/
],
[
/*...branch...*/,
/*...branch...*/,
/*...branch...*/
]
]...then只需删除最后一个then子句(.then(branches => ({repo, branches})))。
https://stackoverflow.com/questions/45387234
复制相似问题