Javascript 中的异步函数调用

Asynchronous function call in Javascript

本文关键字:函数调用 异步 Javascript      更新时间:2023-09-26

我的问题是这个.我是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";

这将仅在函数范围内创建它,而不是在窗口中创建它。