javascript等待多个异步函数调用

时间:2017-11-12 20:46:31

标签: javascript asynchronous

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);
}

我想用p1和p2调用服务,每次服务返回一些值,我把它们放入列表中。我想等待这两个服务完成,即值都在列表中准备好,然后做某事。那个清单。

我不熟悉java脚本异步方法。我尝试过Promise,但没有工作,有人可以为我写一个简单的演示吗?

添加: 我发布了我的实际代码,请帮我解决问题..

    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);
    });

问题是我的代码永远不能运行到Promise回调函数

add:nearby_search_callback只是获取服务返回的数据并将它们放入地图中。

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);
    }
}

2 个答案:

答案 0 :(得分:1)

你只是声明承诺而不是用它们做任何事情。您需要解决或拒绝它们才能完成它们。

我不知道你的“nearby_search_callback”函数是什么样的,但它需要做这样的事情,假设它是一个结构良好的回调,它接受2个参数,如(错误,响应),并最终返回你的数据想要回报承诺:

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));
    });
});

答案 1 :(得分:0)

使用PromisePromise.all。您也可以使用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!