我试图以递归方式从GitHub(使用octonode)获取内容。内容是递归获取的,但是条目承诺的最终结果是undefined
:
获取内容的功能:
_getRepoContent ( user, repo, ref, path ) {
return new Promise( ( resolved, rejected ) => {
this._client.repo( user + "/" + repo, ref ).contents( path, ( err, data ) => {
if ( err ) {
rejected( err );
} else {
resolved( data );
}
} );
} );
}
主要的递归函数:
getContentRec ( sourceDef, data ) {
var results = data || [];
return this._getRepoContent( sourceDef.user, sourceDef.repo, sourceDef.ref, sourceDef.path )
.then( ( data ) => {
let dirs = [];
results = results.concat( data );
data.forEach( ( file ) => {
if ( file.type === "dir" ) {
dirs.push( file );
}
} );
if ( dirs.length > 0 ) {
let promises = [];
dirs.forEach( ( dir ) => {
let def = {
user: sourceDef.user,
repo: sourceDef.repo,
ref: sourceDef.ref,
path: dir.path
};
promises.push( this.getContentRec( def, results ) );
} );
return Promise.all( promises );
} else {
return Promise.resolve( results );
}
} )
.catch( ( err ) => {
return Promise.reject( err );
} );
}
致电:
getContentRec(
{
user: "nodejs",
repo: "node"
}
}).then( (data) => {
// data is undefined
})
有什么想法吗?提前做了很多!
答案 0 :(得分:0)
解决了问题,这是解决方案......:
getContentRec ( sourceDef ) {
return this._getRepoContent( sourceDef.user, sourceDef.repo, sourceDef.ref, sourceDef.path )
.map( ( content ) => {
let def = {
user: sourceDef.user,
repo: sourceDef.repo,
ref: sourceDef.ref,
path: content.path
};
return content.type === "dir" ? this.getContentRec( def ) : content;
} )
.reduce( ( a, b ) => {
return a.concat( b )
}, [] );
}
注意: 这个解决方案是使用蓝鸟而不是纯粹的ES6承诺。