Рекурсивные обещания в ES6 с возвращаемыми значениями

Я пытаюсь получить контент из GitHub (используя октодон) рекурсивно. Контент извлекается рекурсивно, но окончательный результат обещания входа 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
})

Есть идеи? Большое заранее!

1 ответ

Решение

Решил проблему, вот решение...:

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.

Другие вопросы по тегам