0

这是进行串行异步调用的更好方法吗?

http://ajaxian.com/archives/serial-async-xhr

function run() { 
    request1(function () { 
        request2(function () { 
            request3(function () { 
                done(); 
            }); 
        }); 
    }); 
} 

这会导致回调地狱问题吗?

4

1 回答 1

0

This is not bulletproof and just to give you an example.

function ajax(url, callback) { 
    var req = new XMLHttpRequest(); 
    req.open("GET", url, true); 
    req.onreadystatechange = function () { 
        if (this.readyState == 4 && this.status == 200) { 
            if(callback)
            {
                callback(this.responseText);
            }
        } 
    }; 
    req.send(); 
}

as a wrapper, so you end up doing something like

function loadIndex()
{
    ajax('/', function(data){
        alert(data);
        loadIndexAgain();
    });
}

function loadIndexAgain()
{
    ajax('/', function(data){
        alert('more stuff happened');
    });
}

loadIndex();

and your statements will be chained.

fiddle.

于 2012-11-14T15:42:14.167 回答