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, i.e. 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);
}
}