Asynchronously wait for a function to be called

烈酒焚心 提交于 2021-01-29 05:27:45

问题


I'm using the bing-maps JS control and API in WebKit (Android) and WKWebView (iOS).

var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {});
// Binding the event
Microsoft.Maps.Events.addHandler(map, 'viewchangeend', function () { console.log('mapViewchangeend'); });

Later in the code I have a call to map.setView. Because this method is asynchronous I need to wait for the event handler to call the function above.

function SetMapViewLocations(pointsToView) {
  try {
    if (pointsToView.length === 1) {
      map.setView({ center: pointsToView[0], zoom: 17 });
    } else {
      var locationRect = window.Microsoft.Maps.LocationRect.fromLocations(
        pointsToView
      );
      locationRect.height =
        locationRect.height < MIN_BOUNDS_SIZE
          ? MIN_BOUNDS_SIZE
          : locationRect.height;
      locationRect.width =
        locationRect.width < MIN_BOUNDS_SIZE
          ? MIN_BOUNDS_SIZE
          : locationRect.width;
      map.setView({ bounds: locationRect });
      // I need to wait without blocking for the viewchangeend associated method to be called before exiting the method.

    }
  } catch (exception) {
    SetJavascriptException(exception);
  }
}

in c# I would have set an AutoResetEvent in the callback handler method and awaited for it right after calling map.setView(...).

What are my options in Javascript?

I can't see how Promises would help here because I do not see how to construct one in my case.

来源:https://stackoverflow.com/questions/65737817/asynchronously-wait-for-a-function-to-be-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!