ES6 中具有 return 个值的递归承诺

Recursive promises in ES6 with return value(s)

我正在尝试递归地从 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
})

有什么想法吗?提前致谢!

解决了问题,这里是解决方案...:

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 )
        }, [] );
}

注意: 此解决方案使用的是 bluebird 而不是纯 ES6 promises。