【问题标题】:javascript callback function call itself until truejavascript回调函数调用自身直到为真
【发布时间】:2013-01-23 15:54:47
【问题描述】:

我正在运行一个需要继续运行的函数,直到我得到响应示例

exports.getJson = function(url, callback) {

    var loader = Titanium.Network.createHTTPClient();
    loader.open("GET", url);
    loader.onload = function() {
        var response = JSON.parse(this.responseText);
        callback(response);
    };
    loader.onerror = function(e) {
        callback(false);
    };
    // Send the HTTP request
    loader.send();

}

好的,我遇到的问题是它有时会给我一个 null 的响应,我需要它再次运行。

所以我这样称呼它。

    url = 'http://example.com/test.json';
    main.getJson(url, function(response) {
            if(response){
                addData(response);

            }else{      
//return no response i need to run the function again now until it comes back as true
            }       
    });

任何人都可以给我一个好方法来做到这一点,至少尝试 3 次然后返回 false ???

谢谢

【问题讨论】:

标签: javascript json callback


【解决方案1】:

只需将代码放入函数中,然后再次调用即可:

var counter = 0;
function getData() {
    main.getJson('http://example.com/test.json', function(response) {
        if(response){
            addData(response);
        }
        else if (counter < 3) {
            counter++;
            getData();
        }   
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2022-01-03
    相关资源
    最近更新 更多