Массив записей Ajax, когда он заполнен - PullRequest
0 голосов
/ 28 мая 2019

У меня есть глобальная переменная var distances = []. У меня есть функция, чтобы заполнить его, но это занимает некоторое время. И я хочу отправить его в Django view, когда он будет заполнен. Однако из-за асинхронной работы JS я всегда отправляю пустой массив. Как я могу отправить заполненный массив без установки таймаута? Мой код JS

var distances = [] //array where some digits will be stored

function getAllDistances() //function where this digits being put in distances arr
//note that every digit is result of request to API of routing service so it takes 
//some time to get thing done

function ajaxTest(){//function for sending array to Django view
    $.ajax({
        url:'test/',
        type:'POST',
        data:JSON.stringify({distances : distances}),
        dataType: 'json',
        success:function (data) {
            console.log("Ajax test success");
            console.log(data.result.text);//view should return some result
        },

        error:function () {
            console.log("Ajax test failure")
        }
    })
}

function doTheJob(){ //main function 
    getAllDistances();
    ajaxTest();
}

Так что с запросом все в порядке, но он всегда отправляет пустой массив. Можно ли заставить js отправлять заполненный массив без установки таймаута? Я думаю, что обратный вызов сделает что-то здесь, но поправьте меня, если я ошибаюсь


Чтобы было понятнее, я добавлю функцию, которая дает мне расстояния

function getRoutSummary(i, j, q) {
                    var url = 'https://router.project-osrm.org/route/v1/driving/' +
                            coords[i][1] + ',' + coords[i][0] + ';' +
                            coords[j][1] + ',' + coords[j][0] +
                            '?geometries=geojson';
//coord is array of arrays with coordinates like
//[[lat1, long1], [lat2, long2], [lat3, long3]] where lat is latitude and long 
//is longtitude

                    var req = new XMLHttpRequest();    
                    req.responseType = 'json';    
                    req.open('GET', url, true);    
                    req.onload = function () {
                        var jsonResponse = req.response;
                        var distance = jsonResponse.routes[0].distance;
                        distances[q] = distance;
                    };
                    req.send();
            }

А потом я вызываю эту функцию в цикле

function getAllDistances(){
                var q = 0;
                for (var i = 0; i < coords.length; i++){
                    for (var j = 0; j < coords.length; j++){
                        getRoutSummary(i, j, q);
                        q = q + 1;
                    }
                }
                console.log(distances);
            }

1 Ответ

3 голосов
/ 28 мая 2019

Использование обещаний с Promise.all()

distancePromise = [];

function getAllDistances() {
//a loop
var promise = getSingleDistance();
distancePromise.push(promise);
//return a array of promises
return distancePromise
}
//send the distances after all the promises have been resolved
Promise.all(distancePromise).then(function(distances) {
//save the distances
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...