Waiting for async request to return before proceeding Google Apps Script

痞子三分冷 提交于 2020-06-27 13:53:50

问题


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?


回答1:


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();



回答2:


My recomendation would be to use the events module if you are making use of nodejs since it allows you to create an event listener.

So you could do something like

eventEmitter.on('listener_key', function(){
    //your code to be executed after the event
});

funtion emitStuffToListener(){
 eventEmitter.emit('listener_key');
}

EDIT: sorry I missread the post but you can still do event oriented development with Google Apps Event Objects



来源:https://stackoverflow.com/questions/44359158/waiting-for-async-request-to-return-before-proceeding-google-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!