Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for async request to return before proceeding Google Apps Script

Some code in Google Apps Script I am currently producing has a need for an object to be completed with one of the properties being set by the result of an async request. This object, and specifically, this property are then used later down the line. However, because the request has not returned by the time the functions needing that property run, they are not evaluating properly. My code is as follows:

function Thing(val) {
    var self = this

    var createSuccess = function(data) {
        self.foo = data;
    }

    var init = function(val) {
        google.script.run.withSuccessHandler(createSuccess).serverFunc(val);
    };

    init(val);
}

function objStuff() {
    var foobar = new Thing('bar');
    // Do stuff with foobar.foo
}

objStuff();

Currently the stuff using foobar.foo does not work correctly, as the script has not waited for the return value of the script before proceeding.

Is there a way I can wait for the foo property to be evaluated with the async request before proceeding with the rest of my script?

like image 200
dbr Avatar asked Jun 04 '17 21:06

dbr


1 Answers

You can add a callback as a parameter to the constructor:

function Thing(val, cb) {
    var self = this

    var createSuccess = function(data) {
        self.foo = data;
        cb(); // this gets called when data is ready
    }

    var init = function(val) {
        google.script.run.withSuccessHandler(createSuccess).serverFunc(val);
    };

    init(val);
}

function objStuff() {
    var foobar = new Thing('bar', function() {
        // Do stuff with foobar.foo
    });
}

objStuff();
like image 115
Patrick Roberts Avatar answered Sep 28 '22 06:09

Patrick Roberts