如何异步运行函数(XMLHttpRequest)

时间:2016-03-01 23:30:09

标签: javascript ajax callback

我正在从api加载数据,我需要在加载代码后运行一个函数。

function make(query, callback){
    console.log("1");
    var results = makeRequest(query);
    return callback(results);
};

setPoints = function(results){
    console.log("2");
    for(var key in results)
    {
        console.log("3");
        var myLatLng = {lat: key.lat, lng: key.lon};
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            title: 'Hello World!'
        });
    }
};

make(3, setPoints);

makeRequest = function(place) {
    var req = new XMLHttpRequest();
    req.open('GET', "https://trailapi-trailapi.p.mashape.com/?limit=25&q[city_cont]=San+Luis+Obispo&radius=205", true);
    req.setRequestHeader('X-Mashape-Key', 'JwTKoEqkTbmsh3eqT0fBweCHYIAUp1h1GCbjsnkh59Bok0iqOC');
    req.onreadystatechange = function () {
        if (req.readyState === 4) {
            if (req.status >= 200 && req.status < 400) {
                var response = JSON.parse(req.responseText);
                var latLongs = response.places.map(function (key) {
                    return {lat: key.lat, lon: key.lon};
                });
                console.log("Returned");
                return latLongs;
            } else {
                alert("Failed to load " + req.status);
                return null;
            }
        }
    };
    req.send();
}

我想让代码记录“1,返回,2,3”。而是记录“1,2,返回”。

1 个答案:

答案 0 :(得分:2)

解决方案是将回调传递给函数makeRequest。 <{1}}完成后,此回调正在运行。

XMLHttpRequest

问题中的另一个可怕的解决方案是将函数function make(query, callback){ console.log("1"); makeRequest(query,callback); }; setPoints = function(results){ console.log("2"); for(var key in results) { console.log("3"); var myLatLng = {lat: key.lat, lng: key.lon}; var marker = new google.maps.Marker({ position: myLatLng, map: map, title: 'Hello World!' }); } }; make(3, setPoints); makeRequest = function(place, callback) { var req = new XMLHttpRequest(); req.open('GET', "https://trailapi-trailapi.p.mashape.com/?limit=25&q[city_cont]=San+Luis+Obispo&radius=205", true); req.setRequestHeader('X-Mashape-Key', 'JwTKoEqkTbmsh3eqT0fBweCHYIAUp1h1GCbjsnkh59Bok0iqOC'); req.onreadystatechange = function () { if (req.readyState === 4) { if (req.status >= 200 && req.status < 400) { var response = JSON.parse(req.responseText); var latLongs = response.places.map(function (key) { return {lat: key.lat, lon: key.lon}; }); console.log("Returned"); return callback(latLongs); } else { alert("Failed to load " + req.status); return null; } } }; req.send(); } 同步。

在方法makeRequest中,您在第三个参数中定义了AJAX a /同步函数(只应将值XMLHttpRequest.open更改为true)。

false