代码之家  ›  专栏  ›  技术社区  ›  lte__

异步不等待回调中的等待

  •  0
  • lte__  · 技术社区  · 7 年前

    我有一个函数必须是异步的,因为我需要它在某个点上休眠半秒钟,但是我希望它是完全连续的。我正在做以下工作:

    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 只有完成后才能继续。但有了上面的密码, 近景街景 以异步方式运行,我在控制台上获得以下输出:

    Oh
    Hi
    Mark! 
    curentpos before checknearest (42.59678542, -76.15251434999999) 
    curentpos after checknearest (42.59678542, -76.15251434999999)
    success
    no new panodata
    

    意义 近景街景 只完成运行 之后 其他的都运行了,尽管我告诉函数 等待 它(和 getPanoramaByLocation ). 在这个问题上我可能有些误解 等待 ,请帮助我了解为什么会这样!

    0 回复  |  直到 7 年前