简体   繁体   English

javascript等待多个异步function调用

[英]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.我想用 p1 和 p2 调用服务,每次服务返回一些值,我将它们放入列表中。 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.我不熟悉 java 脚本异步方法。 I've tried Promise, but didn't work, anyone can write a simple demo for me?我试过Promise,但是没有用,谁能给我写个简单的demo?

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问题是我的代码永远无法运行到 Promise 回调 function

add: the nearby_search_callback is just fetch the data return by service and put them into a map.补充:nearby_search_callback只是把服务返回的数据拿过来放到一个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: 我不知道您的“ nearby_search_callback”函数是什么样的,但它需要做类似的事情,假设它是一个结构良好的回调,它接受2个参数(例如,err,response),并最终返回要返回的数据在承诺中:

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 . 使用PromisePromise.all You can also use async - await . 您也可以使用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:您可以像这样解决并拒绝 promise:

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, ...]);

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

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