user4411473
user4411473

Reputation: 189

Return multiple values and access them?

How would I structure this to return multiple values (message and name), and be able to access them in the js.html file?

 

--code.gs

function createArtistTable(name)
{
    var message = "test";

    //return message and name
}

--js.html

function openArtistTable(name)
{
    google.script.run
        .withSuccessHandler(openSuccess)
        .withFailureHandler(openFailure)
        .createArtistTable(name)
}

function openSuccess(//have 2 values here -- var1, var2)
{
    console.log(var1);
    console.log(var2);
}

EDIT:

I've fixed the problem. Thank you all for the help and information. This is what I changed: http://pastebin.com/Ci1e8ZWx

Upvotes: 3

Views: 17960

Answers (1)

user6713871
user6713871

Reputation:

A function can only return one value.

So the way to do this is to wrap them together inside an array or object.

function return2Vals()
{
    var var1;
    var var2;
    //Code that does stuff with var1 and var2
    ///
    ///
    //Create an array with the values and return it.
    var results = [var1, var2];
    return results;
}

Using the result:

var vals = return2Vals();
console.log("One of the return values is:", vals[0]);
console.log("The other return value is:", vals[1]);

Alternatively you could use an object and basically do whatever you want by using an object:

function returnSomeValsAsObj()
{
    var var1;
    var var2;
    //Code that does stuff with var1 and var2
    ///
    ///
    //Create an object with the values and return it.
    var results = {primary_result: var1, secondary_result: var2, accompanying_message: "some message"};
    return results;
}

Using:

var results = returnSomeValsAsObj();
console.log(results.primary_result);
console.log(results.secondary_result);
console.log(results.accompanying_message);

Upvotes: 4

Related Questions