Asynchronously wait for a function to be called
Asked Answered
K

0

0

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.

Kleinstein answered 15/1, 2021 at 14:24 Comment(3)
"I need to wait ... before exiting the method" - Why? (What is the XY problem?)Protolithic
because otherwise, the map has not changed yet and subsequent operations would be ran in the previous result of map.setView. I can't see why added that information would add value to help how to solve this synchronisation problem.Kleinstein
Found an answer hereKleinstein

© 2022 - 2024 — McMap. All rights reserved.