等待异步请求返回,然后继续执行Google Apps脚本 [英] Waiting for async request to return before proceeding Google Apps Script

查看:52
本文介绍了等待异步请求返回,然后继续执行Google Apps脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在生成的Google Apps脚本中的某些代码需要使用异步请求的结果设置的属性之一来完成对象.然后,稍后使用此对象,尤其是此属性.但是,由于在需要该属性的功能运行时请求尚未返回,因此它们无法正确评估. 我的代码如下:

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

当前使用foobar.foo的东西无法正常工作,因为脚本在继续操作之前尚未等待脚本的返回值.

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.

在继续执行我的脚本的其余部分之前,有没有办法让我等待异步请求对foo属性进行评估?

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?

推荐答案

您可以将回调作为参数添加到构造函数中:

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

这篇关于等待异步请求返回,然后继续执行Google Apps脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆