1

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

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 ???

谢谢

4

1 回答 1

4

只需将代码放入函数并再次调用它:

var counter = 0;
function getData() {
    main.getJson('http://example.com/test.json', function(response) {
        if(response){
            addData(response);
        }
        else if (counter < 3) {
            counter++;
            getData();
        }   
    });
});
于 2013-01-23T16:03:24.860 回答