Javascript 中的异步函数调用
Asynchronous function call in Javascript
我的问题是这个.我是javascript的新手。我有一个函数可以异步调用谷歌地图API(根据latlng返回位置)。我的代码中的这个函数是MarkerCreaterPlusLocation。此调用返回我在代码中名为 MarkerCreater 的另一个函数中需要的值。但问题是 MarkerCreater 不会停止让 MarkerCreaterPlusLocation 返回值。
为了克服这个问题,我尝试使用回调来执行 MarkerCreater 在异步函数返回值时执行
结构如下:
google.maps.event.addListener(map, 'click',addLatLng); //This code attaches the function to Listener
function addLatLng(event) {
path = poly.getPath();
path.push(event.latLng);
MarkerCreaterPlusLocation(event.latLng,MarkerCreater);//MarkerCreater is the callback function
}
function MarkerCreaterPlusLocation(input,callback){
location="l";
geocoder.geocode({'latLng': input}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
location=results[1].formatted_address;
callback(location,input);//I call the callback function upon the success of the result or otherwise
} else {
location="l";
callback(location,input);
}
} else {
location="l";
callback(location,input);
}
});
}
function MarkerCreater(l,x){
var marker = new google.maps.Marker({
position: x,
title: '#' + path.getLength()+l,
icon: 'images/beachflag.png',
map: map
});
///Some more javascript code
}
我想我在这里犯了错误,因为这似乎不起作用.相反,它给出了一个 404 错误,这使我更难理解它。请帮忙
你的location
变量没有用 var
声明,这意味着它在全局范围内(即窗口)。因此,设置 location
实际上是设置 window.location
,这会导致重定向到 404。
要解决此问题,请将 MarkerCreaterPlusLocation 函数的第一行更改为:
var location="l";
这将仅在函数范围内创建它,而不是在窗口中创建它。
相关文章:
- 递归调用异步函数
- 异步函数调用是否可以在两个同步语句之间完成
- 在异步函数调用过程中,当对象的属性值发生变化时,JavaScript中的对象属性值会发生什么变化
- 根据两个异步函数调用的结果执行
- 循环变量作为异步函数调用中的参数
- 调用异步函数的循环
- 从视图调用异步加载模块函数
- RSVP.js - 数组上的多个异步函数调用
- Javascript 中的异步函数调用
- 两个异步函数调用填充同一个数组
- Javascript:使用 jQuery 的异步函数调用
- 在循环中调用异步函数
- 并行调用异步/等待函数
- NodeJS:调用异步函数时谁做异步工作
- jQuery 文档就绪 - 函数调用:顺序或异步
- 调用异步函数 befrore 服务器开始侦听
- 使用Jquery$When进行异步和同步函数调用
- 页面重定向后调用异步成功函数
- 如何在node.js可读流中调用异步函数
- 在nodejs中,是否有更好的设计模式来同步调用异步函数