我有一个必须异步的函数,因为我需要它在某个时刻睡眠半秒钟,但是然后我希望它是完全顺序的。我正在执行以下操作:
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");
}
我希望checkNearestStreetView
能够在代码继续运行之前完全运行,因此我正在尝试await
并仅在完成后才继续运行。但是使用上面的代码,checkNearestStreetView
异步运行,并且在控制台上得到以下输出:
Oh
Hi
Mark!
curentpos before checknearest (42.59678542, -76.15251434999999)
curentpos after checknearest (42.59678542, -76.15251434999999)
success
no new panodata
意味着checkNearestStreetView
仅在 之后运行完毕,即使我告诉函数await
(和getPanoramaByLocation
)也要运行。我可能对await
的主题有误解,请帮助我了解为什么会这样发生!