繁体   English   中英

在继续打字稿之前等待函数执行完成

[英]Wait function execution completion before continuing in typescript

我有一个计算两点之间路线的函数。

 public ClosestPoint(waypoint,currentLocation){
     let distances = [];
     for(var i=0; i< waypoint.length;i++){
         debugger

         var rWP1 = new L.Routing.Waypoint;
         rWP1.latLng = currentLocation;    

         var rWP2 = new L.Routing.Waypoint;
         rWP2.latLng = waypoint[i];   

         var myRoute =L.Routing.mapbox('access-token');
         myRoute.route([rWP1, rWP2], function(err, routes) {
             debugger
             var distance = routes[0].summary.totalDistance;
             distances.push(distance);
         });
     }  
     var minDistance=Math.min.apply(Math, distances)
     console.log("distances "+distances);
 }

但我面临的问题是myRoute.route ()函数在ClosestPoint()执行后执行,所以我无法正确获得距离。 我希望myRoute.route()在 for 循环内执行,然后开始下一次迭代。

是否可以? 如果是,那么如何? 或者它有其他解决方案吗?

尝试将此函数包装在Promise对象中

  function get_routes(rWP1,rWP2) {
    return new Promise((resolve, reject) => {
      myRoute.route([rWP1, rWP2], function (err, routes) {
        if (err) {
          reject(err);
        } else {
          resolve(routes)
        }
      });
    })
  }

之后你可以在 async 函数中使用await或者你可以构建 promises 对象的数组并使用Promise.all

我们要澄清一件事。 任何在 javascript 中带有回调的函数都不会是同步的。 所以,你需要使用async

async.eachSeries(waypoint, function(item, nextitem) {
    async.waterfall([
         function(callback) {
             var rWP1 = new L.Routing.Waypoint;
             rWP1.latLng = currentLocation;    
             var rWP2 = new L.Routing.Waypoint;
             rWP2.latLng = item;
             callback(null, [rWP1, rWP2]);
         },
         function(data, callback) {
             myRoute.route([rWP1, rWP2], function(err, routes) {
                  var distance = routes[0].summary.totalDistance;
                  distances.push(distance);
                  if(distances.length === waypoint.length){
                      var minDistance=Math.min.apply(Math, distances)
                      console.log("distances "+distances);
                  } else {
                      callback(null, 3); //3 is just a random value you can give
                  } 
             });
         }
    ],nextitem)         
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM