问题
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