如何在Javascript中执行ABCD功能之前等待所有Promises完成?

时间:2019-02-07 22:39:28

标签: javascript asynchronous promise async-await

每次我要求与Google API保持距离时,我都会创建一个新的Promise。我希望所有Promises都解决,然后调用ABCD函数吗?现在它立即调用ABCD函数。

async function RunBookings(Records) {
  for (var k = 0; k < gDestinationsArray.length; k++) {
    console.log('k' + k);
    let promise = new Promise(function(resolve, reject) {
      console.log('new Promise');
      var DistanceService = new google.maps.DistanceMatrixService();
      DistanceService.getDistanceMatrix({
        origins: gOriginsArray[k],
        destinations: gDestinationsArray[k],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
      }, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          console.log(response);
          var results = response.rows[0].elements; //console.log(results );
          for (var l = 0; l < results.length; l++) {
            gDistanceArray.push(results[l].distance.text);
          }
          setTimeout(function() {
            resolve('Good promise');
          }, 10000);
        } else if (status === google.maps.DirectionsStatus.OVER_QUERY_LIMIT) {
          console.log('OVER_QUERY_LIMIT');
          console.log(response);
          console.log(status);
          reject(Error("Bad promise"));
        } else {
          console.log('BAD');
          console.log(response);
          console.log(status);
          reject(new Error("Bad promise"));
        }
      });
    });
    let result = await promise;
  }
}

function ABCD() {

}

RunBookings(Records);
ABCD();

2 个答案:

答案 0 :(得分:2)

  

您应该等待与 Promise.all(promises)

的所有承诺。
function RunBookings(Records) {
  const promises = [];

  for (var k = 0; k < gDestinationsArray.length; k++) {
    let promise = new Promise(function(resolve, reject) {

    ..... your code....

    promises.push(promise);
  }

  return promises;
}

function ABCD() {
}


Promise.all(RunBookings(Records))
   .then( val => {
       ABCD();
   });

或使用async / await

async function RunBookings(Records) {
  const promises = [];

  for (var k = 0; k < gDestinationsArray.length; k++) {
    let promise = new Promise(function(resolve, reject) {

    ..... your code....

    promises.push(promise);
  }

  return promises;
}

function ABCD() {
}


let result = await RunBookings(Records);
ABCD();

或者如果您想返回一个承诺

async function RunBookings(Records) {
  await Promise.all(gDestinationArray.map(async (gDestination) => {
           ............
  }));
}

RunBookings(Records);
ABCD();

答案 1 :(得分:1)

RunBookingsasync function,因此会返回一个承诺(它不会阻塞!),因此请使用

RunBookings(Records).then(ABCD);