Search code examples
javascriptbluebirdes6-promise

how can I return the array from this promise?


I have tried a few methods and been reading round but I cannot seem to figure out how to return the names array from this function.

function getNames(oauth2Client, docs) {
const api = x('v1');

let names = [];

return Promise.each(docs, function(doc) {
        let req = api.users.messages.get;

        let options = ({
            auth: oauth2Client,
            'userId': 'me',
            'id': doc.id
        });

        return Promise.promisify(req)(options).then(function(response) {
            for (y = 0; y < response.names.length; y++) {              
                names.push(response.names[y].toLowerCase());                
            }
        })
        .catch(function (err) {
            console.log('An error occured: ' + err.message);
            throw err;
        });
    });
}

Solution

  • I'm not sure what Promise library you are using as it appears non-standard, but something like this I think is what you want. I added comments for what's going on - you might have to change those lines of code to suit your promise library.

    function getNames(oauth2Client, docs) {
        const api = x('v1');
        const names = [];
        // create a stack of promises
        const stack = [];
        docs.forEach(doc => {
            let req = api.users.messages.get;
            let options = ({
                auth: oauth2Client,
                'userId': 'me',
                'id': doc.id
            });
            // push each promise onto the stack
            stack.push(
                Promise.promisify(req)(options).then(function(response) {
                    for (y = 0; y < response.names.length; y++) {              
                        names.push(response.names[y].toLowerCase());                
                    }
                })
                .catch(function (err) {
                    console.log('An error occured: ' + err.message);
                    throw err;
                })
            );
        });
        // Wait for all promises in the stack to finish, and then
        // return the names array as the final value.
        return Promise.all(stack).then(() => names);
    }