[英]Wait for asynchronous task to complete before continuing?
I'm trying to get location coordinates via the google maps javascript api, which happens asynchronously. 我正在尝试通过Google Maps JavaScript API获取位置坐标,这是异步发生的。
Here is my function for retrieving: 这是我要检索的功能:
function getCoords(input_address)
{
var geocoder = new google.maps.Geocoder();
var addr = {
address: input_address
};
var callback = function(result, status)
{
if (status == "OK") {
var coords = result[0]['geometry']['location'];
console.log(coords.toUrlValue());
}
};
geocoder.geocode(addr,callback);
}
I want to submit the coordinates along with the rest of a form via an ajax function. 我想通过ajax函数将坐标与表单的其余部分一起提交。
However, testing out the following: 但是,请测试以下内容:
form.submit(function(event){
event.preventDefault();
var addr = $("input[type='text']").val();
getCoords(addr);
console.log('should wait');
});
Outputs: 输出:
should wait
coordinates
Is there a way to make sure the getCoords
function completes before the next instruction is executed? 有没有一种方法可以确保在执行下一条指令之前完成
getCoords
函数?
Use the callback function for this purpose, do your other job after executed geocoder.geocode();
为此使用回调函数,在执行
geocoder.geocode();
之后执行其他工作geocoder.geocode();
something like 就像是
function getCoords(input_address){
......
......
geocoder.geocode(addr, function (){
doYourJobNow(); //as suggested by tgun926
});
}
function doYourJobNow(){
console.log('should wait');
}
//result would be
//coordinates
//should wait
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.