I have a function that has to be async because I need it to sleep at some point for half a second, but then I'd just like it to be completely sequential. I'm doing the following:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
checkNearestStreetView(panoData){
if(panoData){
if(panoData.location){
if(panoData.location.latLng){
console.log("new panodata" + panoData.location.latLng);
this.currentpos = panoData.location.latLng;
console.log("new panodata:" + this.currentpos);
}
}
} else {
this.currentpos = null;
console.log("no new panodata");
}
}
async updateLocation(feature, layer) {
console.log("Oh");
await sleep(500);
console.log("Hi");
console.log("Mark!");
var webService = new google.maps.StreetViewService();
var checkaround = 50;
...
console.log("curentpos before checknearest " + this.currentpos);
await webService.getPanoramaByLocation(this.currentpos, checkaround, await this.checkNearestStreetView.bind(this));
console.log("curentpos after checknearest " + this.currentpos);
console.log("success");
}
I would like checkNearestStreetView
to run completely before the code continues to run, so I'm trying to await
it and only continue once it's done. But with the above code, checkNearestStreetView
runs in async, and I get the following output on the console:
Oh
Hi
Mark!
curentpos before checknearest (42.59678542, -76.15251434999999)
curentpos after checknearest (42.59678542, -76.15251434999999)
success
no new panodata
Meaning checkNearestStreetView
only finishes running after everything else ran, even though I told the function to await
it (and getPanoramaByLocation
). There might be something I'm misunderstanding on the subject of await
, please help me learn why this happens this way!