0

也许您可以用一种优雅的方式将两个函数链接在一起。

  1. 第一个使用“getScript”从外部 url 检索一个值。
  2. 第二个,等待第一个函数。获得该价值并对其进行处理。

这是我尝试过的,除了等待部分(他们最重要)之外,一切都应该工作:)

我已经评论了代码以便更好地理解:

/**
 * Test Class.
 */
 var Test = function() {

    var cookieEmail;

    this.init = function() {

        var script = 'http://www.script.com';

        jQuery.getScript(script, function(){
            cookieEmail = typeof (functionOnScriptCom) == 'undefined' ? '' : functionOnScriptCom('V_ElqEmailAddress');
        }
    }

    this.init2 = function(){
        // I want to do something with the variable "cookieEmail", after it has been retrieved using getScript.
        cookieEmail = cookieEmail.toLowerCase();
    }

 }

 jQuery(document).ready(function(){

    var test = new Test();

    test.init();
    // I need a way to wait for -- test.init -- getScript function to retrieve the ---cookieEmail--- value.
    // When cookieEmail's value has been retrieved, I want to be able to call:

    test.init2();

 });
4

3 回答 3

3

好吧,它不会等待,因为getScript是异步调用,因此您应该修改init()以接受回调函数,然后init2在该回调中运行:

this.init = function(callback) {
    var cookieEmail;
    var script = 'http://www.script.com';

    jQuery.getScript(script, function(){
        cookieEmail = typeof (functionOnScriptCom) == 'undefined' ? '' : functionOnScriptCom('V_ElqEmailAddress');
        callback(cookieEmail);
    }
}

//Modify init2 to accept a param
this.init2 = function(cookieEmail){

现在你可以这样做:

test.init(function(data) {
    init2(data);
}
于 2013-09-19T17:23:41.750 回答
0

我会将回调传递给成功init执行后将getScript执行的函数。像这样的东西:

var Test = function() {

    var cookieEmail;

    this.init = function( callback ) {

        var script = 'http://www.script.com';

        jQuery.getScript(script, function(){
            cookieEmail = typeof (functionOnScriptCom) == 'undefined' ? '' : functionOnScriptCom('V_ElqEmailAddress');
            callback();
        }
    }

    this.init2 = function(){
        // I want to do something with the variable "cookieEmail", after it has been retrieved using getScript.
        cookieEmail = cookieEmail.toLowerCase();
    }

}

jQuery(document).ready(function(){

    var test = new Test();

    test.init( function() { test.init2(); });
});
于 2013-09-19T17:24:05.103 回答
0

来自 AJAX(包括getScriptJSONP)的响应始终是异步的。所以使用承诺模式:

var test = {
    init: function() {
        var script = 'http://www.script.com';
        return jQuery.getScript(script).then(function(){
            return typeof (functionOnScriptCom) == 'undefined' ? '' : functionOnScriptCom('V_ElqEmailAddress');
        });
    },
    init2: function(promise){
        return promise.then(function(cookieEmail) {
            // do something with `cookieEmail` when it has arrived
            return cookieEmail.toLowerCase();
        });
    }
};

test.init2(test.init());
于 2013-09-19T17:29:36.713 回答