javascript - 填充时的Ajax发布数组
问题描述
我有全局变量var distances = []
。我有填充它的功能,但需要一些时间。我想在它填满时将它发送到 Django 视图。但是由于 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);
}
解决方案
使用 承诺_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
})
推荐阅读
- python - 在 3D 中找到圆盘的交点
- android - Flutter“正在运行 Gradle 任务 'assembleDebug'...”(启动 Gradle 守护程序)永无止境
- azure-iot-hub - 从 github 下载 - 似乎缺少一个目录 (azure-iot-sdk-c)
- openpgp - 无法使用从密钥服务器 (keys.openpgp.org) 检索到的密钥 (gpgme)
- ui-automation - 无法通过剧作家执行空手道脚本
- azure - Azure AD 对本地应用程序进行身份验证(令牌转换服务和类似服务)
- javascript - 根据 2 个值和 1 对对象的 Javascript 数组进行排序
- solidity - 通过 javascript 计算 uniswap 对地址
- typescript - 如何根据泛型输入类型返回类型?
- javascript - Safari 14“Safari 无法下载此文件”