简体   繁体   中英

javascript waiting for multiple asynchronous function call

var p1;
var p2;
var service;
var list=[];

.........

service.call(p1,call_back);
service.call(p2,call_back);
//then do sth with the list

funciton call_back(results) {
    list.concat(results);
}

I want to call the service with p1 and p2, each time the service return some values and I put those into list. I want to wait for these two service finished, ie the values are all prepared in the list, then do sth. with that list.

I'm not familiar with java script asynchronous approach. I've tried Promise, but didn't work, anyone can write a simple demo for me?

add: I post my actual code, and please help me figure my problem..

    let place1 = auto1.getPlace();
    let place2 = auto2.getPlace();
    if (!place1.geometry || !place2.geometry) {
        let wrong_place_name = place1.geometry ? place2.name : place1.name;
        window.alert("No details available for input: '" + wrong_place_name + "'");
        return;
    }
    let job1 = new Promise(function () {
        service.nearbySearch({
            location: place1.geometry.location,
            radius: 20000,
            type: ['real_estate_agency']
        }, nearby_search_callback);
    });
    let job2 = new Promise(function () {
        service.nearbySearch({
            location: place2.geometry.location,
            radius: 20000,
            type: ['real_estate_agency']
        }, nearby_search_callback);
    });

    Promise.all([job1, job2]).then(function () {
        console.log('test');
        let agency_arr = Array.from(agency_list.values());
        console.log(agency_arr.length);
        agency_arr.sort(function (x, y) {
            let total_dist1 = dist(x.geometry.location, place1.geometry.location) + dist(y.geometry.location, place1.geometry.location);
            let total_dist2 = dist(x.geometry.location, place2.geometry.location) + dist(y.geometry.location, place1.geometry.location);
            return total_dist1 - total_dist2;
        });
        agency_arr.map(createMarker);
    });

The problem is the my code can never run to the Promise call back function

add: the nearby_search_callback is just fetch the data return by service and put them into a map.

function nearby_search_callback(results, status) {

    if (status === google.maps.places.PlacesServiceStatus.OK) {
        results.map(function (a) {
            agency_list.set(a.id, a);
        });
        // console.log(agency_list.size);
    }
}

You're just declaring promises and not doing anything with them. You need to resolve or reject them for them to ever complete.

I don't know what your "nearby_search_callback" function looks like, but it needs to do something like this instead, assuming it's a well structured callback that takes 2 parameters like (err, response), and eventually returns the data you want to return in the promise:

let job1 = new Promise(function (resolve, reject) {
    service.nearbySearch({
        location: place1.geometry.location,
        radius: 20000,
        type: ['real_estate_agency']
    }, function(err, data) { 
        if (err) reject(err);
        resolve(nearby_search_callback(null, data));
    });
});

Use Promise and Promise.all . You can also use async - await .

const asyncronized = thing => new Promise((resolve, reject) => {
    service.call(thing, resolve);
});
// Asynchronize them.

Promise.all([asyncronized(p1), asyncronized(p2)]).then(final_callback);
// Go!

For future folks stuck on this. You can resolve and reject the promise like this:

const job1 =  new Promise(
      (
          resolve: (result: google.maps.places.PlaceResult[]) => void,
          reject: (status: google.maps.places.PlacesServiceStatus) => void
      ) => {
        placesService.findPlaceFromQuery(nameRequest, (results, status) => {
              if (status == google.maps.places.PlacesServiceStatus.OK) {
                  resolve(results);
              } else {
                  reject(status);
              }

          });
      });

const allResults = await Promise.all([job1, ...]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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