Search code examples
javascriptnode.jspromisegmail-api

How to handle Gmail-API promises and returns?


I'm currently trying to do something with the Gmail-API but unfortunately I'm not able to create a getter method because the google functions are asynchronous.

So I basically have two functions:

function doSomething() {
    let mailArray = [];

    fs.readFile('credentials.json', (err, content) => {
        mailArray = getBackupsMails(authorize(JSON.parse(content)));
    });

    // do something with mailArray
}
function getMails(auth) {
    let mailArray = [];

    gmail.users.messages.list({auth: auth, userId: 'me'}, function(err, response) {
        let messagesArray = response.data.messages;

        messagesArray.forEach((message) => {
            gmail.users.messages.get({ auth: auth, userId: 'me', id: message.id }, function(err, response) {
                message_raw = response.data.snippet;
                text = message_raw.substring(16, 55);
                mailArray.push(text);
            });
        });

    });

    return mailArray;
}

Unfortunately the mailArray is undefined. How can I get the filled array?


Solution

  • Since the API-call is asynchronous, you can only access the filled array once the API call has completed. Currently, return mailArray; gets executed before the API call is done.

    To get the actual emails to the caller of getMails(), you will need to make getMails() asynchronous too - either with async/await, promises, or a callback.

    As ponury-kostek said, see How do I return the response from an asynchronous call? for details.