I'm trying to make a function that returns the results of a SOAP call (using npm-soap in combination with node.js). The problem is that the function returns undefined because the SOAP call isn't finished yet when the return statement is reached.
I tried putting the return statement in the SOAP call callback itself, but then it returns undefined. I think this is because the return statement should be in the outer function instead of the inner function, just like I did in the example below. A console.log() in the SOAP call callback outputs the right data, so I know it's there.
How do I make the return statement wait on the inner SOAP call? Thanks!
var config = require('./config.js');
var soap = require('soap');
function getInvoices() {
    let invoices;
    // Connect to M1
    soap.createClient(config.endpoint, function(err, client) {
        // Log in
        client.login(
            { 
                username: config.username,
                apiKey: config.password
            }, 
            function(err, loginResult) {
            // Get invoices
            client.salesOrderInvoiceList(
                { 
                    sessionId: loginResult.loginReturn.$value
                }, 
                function(err, invoiceResult) {
                    // Save invoices
                    invoices = invoiceResult;
                    console.log(invoices); // <- Returns the right data
                    // Log out
                    client.endSession(
                        { 
                            sessionId: loginResult.loginReturn.$value
                        },
                        function(err, logoutResult) {
                        }
                    );
                }
            );
        });
    });
    // Return invoices
    return invoices; // <- Returns undefined
}
console.log(getInvoices(); // <- So this returns undefined as well
 
    