等待Promise时事件参考丢失

时间:2019-01-10 16:22:32

标签: javascript here-api

我有一个函数,可以接收事件并在该事件属性上添加一些内容:

map.addEventListener('contextmenu', async (e) => {
   const { Label } = await reverseGeoCode(getPosition.lng, getPosition.lat)

   e.items.push(addContextItem(Label, null)))
})

但是由于某种原因,e在等待Label返回时迷路了。为什么会这样?

1 个答案:

答案 0 :(得分:0)

您是否尝试过这种方式:

// add context menu listner  
map.addEventListener('contextmenu', function(e){
    // reverse geocode at the point of click if not already
    if (notReverseGeocoded) {
        clickCoords = map.screenToGeo(e.viewportX, e.viewportY);
        var reverseGeocodingParameters = {
            prox: clickCoords.lat + "," + clickCoords.lng + ",200",
            mode: 'retrieveAddresses',
            maxresults: 1,
            language: 'en'
        };
        geocoder.reverseGeocode(reverseGeocodingParameters, function(result){
            try {
                address = result.Response.View[0].Result[0].Location.Address.Label;
                notReverseGeocoded = false;
                // disptach to the context menu event again to add results to the 
                // context menu
                map.dispatchEvent(e);
            } 
            catch (e) {
                console.log(e);
            }
        }, function(e){
            console.log(e);
        });

    }