Kousha
Kousha

Reputation: 36189

Javascript to return a function, but also get a variable

I don't know how to properly phrase it, so I'll just give the example:

I have generator functions that behave as such:

function generateSomething(app) {
    return new Promise(function (resolve, reject) {
        var cookie;

        var login = function (async_cb) {
            // Ajax call to login
            // This would return a cookie that I need to use for subsequent calls
        }

        var generate = function (async_cb) {
            // This will use the cookie returned from login
        }

        async.series([
            login, 
            generate,
            generate,
            generate,
            function () {
                resolve();
            }
        ]);
    });
}

I'll be having many generator files, and there are many functions similar in all of them (for instance, the login). So I'd rather refactor that out into a global helper class. I also really like the async library because of is clean format.

Here comes my problem...

To refactor the login function, I have:

var Helper = {};
module.exports = Helper;

Helper.login = function (app) {
    return function (async_cb) {
        // Ajax to login
        // Once done, call
        aysnc_cb();
    }
}

And I would use it in my generator function as:

var Helper = require('./helper');
function generateSomething(app) {
    return new Promise(function (resolve, reject) {
        var cookie;

        var generate = function (async_cb) {
            // This will use the cookie returned from login
            // Once done, call
            aysnc_cb();
        }

        async.series([
            Helper.login(app), 
            generate,
            generate,
            generate,
            function () {
                resolve();
            }
        ]);
    });
}

The problem though is how do I also return cookie in this example? I realize I would use a Promise and return the result with resolve() but that would mean I cannot use the clean look of async.series([Helper.login, ...]).

Help is appreciated.

Upvotes: 0

Views: 42

Answers (2)

Steven Leimberg
Steven Leimberg

Reputation: 785

Try setting setting and checking for a global variable with a specific name or within a certain object?

window.specialobject.specialvariable = 'something';

and then deleting the variable when you are done?

delete window.specialobject.specialvariable;

just an idea considering this is async.

Upvotes: 0

Steven Leimberg
Steven Leimberg

Reputation: 785

The only way I know of to return two objects/values from a single function is to return an array, or object with named values:

return { 'fn':yourobject, 'variable':cookie }

Upvotes: 1

Related Questions