等待所有异步调用,然后返回ES5纯JS?

时间:2018-11-14 13:12:37

标签: javascript asynchronous

此函数中有两个异步调用(@ .then(...)),它们多次循环。如何重新构造此函数以确保仅在所有调用完成后才返回?我知道我可以在ES6中使用异步/等待,但是我只能在没有库的情况下使用ES5。

function queryLayer(layer, buffer){
  var query = layer.createQuery();
  query.geometry = buffer;
  query.spatialRelationship = "intersects";

  layer.queryFeatures(query).then(function(results){
    console.log(results.features[0].sourceLayer.title, results.features.length);
    if(!results.features.length > 0) return false;
    var features = results.features;
    features.forEach(function(feature){
      feature.distance = calculateDistance(buffer.centroid, feature.geometry);
      locator.locationToAddress(feature.geometry).then(function(x){
        feature.address = x.address;
      });
    });
    return features;
  });
}

1 个答案:

答案 0 :(得分:0)

let promises = []
features.forEach(function(feature){
      promises.push(locator.locationToAddress(feature.geometry))
});

Promise.all(promises).then(x => {
  /* ... */
}