简体   繁体   中英

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;
        });
    });
}

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);
}

Simply add

return Promise.each(…)
.then(function() {
    return names;
});

that causes the returned promise to fulfill with the names array.

However I would recommend that you don't use a global array across the each loop, especially if you care about the order of results. Instead, resolve every promise with a value, use map instead of each , and combine the results in the end:

const api = x('v1');
const getUserMessages = Promise.promisify(api.users.messages.get);

function getNames(oauth2Client, docs) {
    return Promise.map(docs, doc =>
        getUserMessages({
            auth: oauth2Client,
            'userId': 'me',
            'id': doc.id
        })
        .then(response =>
            response.names.map(name => name.toLowerCase());
        )
    )
    .then(nameArrays =>
        [].concat(...nameArrays)
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM