将回调转变为承诺

时间:2014-02-23 10:30:26

标签: javascript

我正在使用google maps api,这段代码正在异步返回一个地方列表。如何在调用所有数据时调用此函数并使其触发?这是我迄今为止所尝试过的 -

$.search = function(boxes) {

    function findNextPlaces(place_results, searchIndex) {
        var dfd = $.Deferred();
        if (searchIndex < boxes.length) {
            service.radarSearch({
                bounds: boxes[searchIndex],
                types: ["food"]
            }, function (results, status) {
                if (status != google.maps.places.PlacesServiceStatus.OK) {
                    return dfd.reject("Request["+searchIndex+"] failed: "+status);
                }
                console.log( "bounds["+searchIndex+"] returns "+results.length+" results" );
                for (var i = 0, result; result = results[i]; i++) {
                    var marker = createMarker(result);
                    place_results.push(result.reference); // marker?
                }
            });
            return dfd.then(findNextPlaces);
        } else {
            return dfd.resolve(place_results).promise();
        }
    }

    return findNextPlaces([], 0);
};

4 个答案:

答案 0 :(得分:5)

为了回答标题隐含的问题,“将回调转化为承诺”,简单的回答是使用一个非常简单的“promisifier模式”(我的术语),其中延迟的.resolve()方法被建立为回调:

回拨原始来电:

obj.method(param1, param2, ... paramN, callbackFn);

使用延迟包装器转换调用:

$.Deferred(function(dfd) {
    obj.method(param1, param2, ... paramN, dfd.resolve);
}).promise();

无论obj.method是否异步,都可以这样做。优点是您现在可以在同一代码块中使用Deferreds / promises的完全可链接性,或者更常见的是,在其他地方分配或返回生成的Promise。

这是一种在这个问题的情况下可以使用模式的方法......

$.search = function(boxes, types) {

    function findPlaces(box) {
        var request = {
           bounds: box,
           types: types
        };

        //***********************
        // Here's the promisifier
        //***********************
        return $.Deferred(function(dfd) {
            service.radarSearch(request, dfd.resolve);
        }).promise();
        //***********************
        //***********************
        //***********************
    }

    function handleResults(results, status, searchIndex) {
        var message, marker;
        if (status != google.maps.places.PlacesServiceStatus.OK) {
            message = "bounds[" + searchIndex + "] failed : " + status;
        }
        else {
            message = "bounds[" + searchIndex + "] returns " + results.length + " results";
            for (var i = 0, result; result = results[i]; i++) {
                marker = createMarker(result);
                place_Results.push(result.reference);
            }
        }
        return message;
    }

    var place_Results = [],
        p = $.when();//resolved starter promise

    //This concise master routine comprises a loop to build a `.then()` chain.
    $.each(boxes, function(i, box) {
        p = p.then(function() {
            return findPlaces(box).done(function(results, status) {
                // This function's arguments are the same as the original callback's arguments.
                var message = handleResults(results, status, i);
                $('#side_bar').append($("<div/>").append(message));
            });
        });
    });

    //Now, chain a final `.then()` in order to make the private var `place_Results` available via the returned promise. For good measure, the `types` array is also repeated back.
    return p.then(function() {
        return {
            types: types,
            results: place_Results
        };
    });
};

$.search()现在可以按如下方式使用:

$.search(boxes, ["food"]).done(function(obj) {
    alert(obj.results.length + ' markers were a added for: "' + obj.types.join() + '"');
});

DEMO - 注意:由于jQuery 1.8.3上jQuery.Deferred.then()的重大修订,因此需要jQuery 1.8.3+。

这与问题中的代码不完全相同,但可能有助于诊断您报告的问题。特别是:

  • 它不会因错误而停止
  • 它会在'#side_bar'中添加和错误消息。

调整代码以做你想做的事情应该很简单。

答案 1 :(得分:1)

当前的JavaScript:

var map = null;
var boxpolys = null;
var directions = null;
var routeBoxer = null;
var distance = null; // km
var service = null;
var gmarkers = [];
var infowindow = new google.maps.InfoWindow();

var promises = [];

function MyPromise() {
    return this;
};

MyPromise.prototype.promise = function () {
    var p = promises[this] || {
        then: []
    };

    promises[this] = p;

    return this;
};

MyPromise.prototype.then = function (func) {
    this.promise();

    promises[this].then.push(func);

    return this;
};

MyPromise.prototype.resolve = function () {
    this.promise();

    var then = promises[this].then;

    for (var promise in then) {
        then[promise].apply(this, arguments);
    }

    return this;
};

function initialize() {
    // Default the map view to the continental U.S.
    var mapOptions = {
        center: new google.maps.LatLng(40, -80.5),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoom: 8
    };

    map = new google.maps.Map(document.getElementById("map"), mapOptions);
    service = new google.maps.places.PlacesService(map);

    routeBoxer = new RouteBoxer();

    directionService = new google.maps.DirectionsService();
    directionsRenderer = new google.maps.DirectionsRenderer({
        map: map
    });
}

function route() {
    var dfd = new MyPromise().promise();

    // Clear any previous route boxes from the map
    clearBoxes();

    // Convert the distance to box around the route from miles to km
    distance = parseFloat(document.getElementById("distance").value) * 1.609344;

    var request = {
        origin: document.getElementById("from").value,
        destination: document.getElementById("to").value,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    }

    // Make the directions request
    directionService.route(request, function (result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsRenderer.setDirections(result);

            // Box around the overview path of the first route
            var path = result.routes[0].overview_path;
            var boxes = routeBoxer.box(path, distance);
            // alert(boxes.length);
            drawBoxes(boxes);
            // findPlaces(boxes,0);
            $.search(boxes, 0).then(function (p) {
                console.log("done", p);
            }).then(dfd.resolve);
        } else {
            alert("Directions query failed: " + status);
        }
    });

    // $.when(findPlaces()).done(function(){
    //  console.log("done");
    // });

    return dfd;
}

// Draw the array of boxes as polylines on the map
function drawBoxes(boxes) {
    boxpolys = new Array(boxes.length);
    for (var i = 0; i < boxes.length; i++) {
        boxpolys[i] = new google.maps.Rectangle({
            bounds: boxes[i],
            fillOpacity: 0,
            strokeOpacity: 1.0,
            strokeColor: '#000000',
            strokeWeight: 1,
            map: map
        });
    }
}


$.search = function findPlaces(boxes, searchIndex) {
    var dfd = new MyPromise().promise();

    var request = {
        bounds: boxes[searchIndex],
        types: ["food"]
    };

    window.place_Results = [];

    service.radarSearch(request, function (results, status) {
        if (status != google.maps.places.PlacesServiceStatus.OK) {
            alert("Request[" + searchIndex + "] failed: " + status);
            return;
        }

        document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns " + results.length + " results<br>"

        for (var i = 0, result; result = results[i]; i++) {
            var marker = createMarker(result);
            place_Results.push(result.reference);
        }

        searchIndex++;

        if (searchIndex < boxes.length) findPlaces(boxes, searchIndex);

        if (place_Results.length > 0) {
            dfd.resolve(place_Results);
        }
    });

    return dfd;
}

// Clear boxes currently on the map
function clearBoxes() {
    if (boxpolys != null) {
        for (var i = 0; i < boxpolys.length; i++) {
            boxpolys[i].setMap(null);
        }
    }
    boxpolys = null;
}

function createMarker(place) {
    var placeLoc = place.geometry.location;
    if (place.icon) {
        var image = new google.maps.MarkerImage(
        place.icon, new google.maps.Size(71, 71),
        new google.maps.Point(0, 0), new google.maps.Point(17, 34),
        new google.maps.Size(25, 25));
    } else var image = null;

    var marker = new google.maps.Marker({
        map: map,
        icon: image,
        position: place.geometry.location
    });
    var request = {
        reference: place.reference
    };
    google.maps.event.addListener(marker, 'click', function () {
        service.getDetails(request, function (place, status) {
            // console.log(place);
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                var contentStr = '<h5>' + place.name + '</h5><p>' + place.formatted_address;
                if ( !! place.formatted_phone_number) contentStr += '<br>' + place.formatted_phone_number;
                if ( !! place.website) contentStr += '<br><a target="_blank" href="' + place.website + '">' + place.website + '</a>';
                contentStr += '<br>' + place.types + '</p>';
                infowindow.setContent(contentStr);
                infowindow.open(map, marker);
            } else {
                var contentStr = "<h5>No Result, status=" + status + "</h5>";
                infowindow.setContent(contentStr);
                infowindow.open(map, marker);
            }
        });

    });
    gmarkers.push(marker);
    var side_bar_html = "<a href='javascript:google.maps.event.trigger(gmarkers[" + parseInt(gmarkers.length - 1) + "],\"click\");'>" + place.name + "</a><br>";
    document.getElementById('side_bar').innerHTML += side_bar_html;
}

initialize();

document.getElementById('route').onclick = route;

有关完整的工作文档,请参阅http://jsfiddle.net/zsKnK/7/

答案 2 :(得分:1)

...应始终解决jQuery-Deferred。因此,在您的函数中完成任务后,使用您的参数调用“dfd.resolve()”,您必须在then-callback-function中使用。

答案 3 :(得分:1)

您在第一次请求后解析延迟,而不是等待递归调用的结果。要做到这一点,你需要链接它们。此外,您不应该为place_Results使用全局变量。

$.search = function(boxes) {

    function findNextPlaces(place_results, searchIndex) {
        var dfd = $.Deferred();
        if (searchIndex < boxes.length) {
            service.radarSearch({
                bounds: boxes[searchIndex],
                types: ["food"]
            }, function (results, status) {
                if (status != google.maps.places.PlacesServiceStatus.OK) {
                    return dfd.reject("Request["+searchIndex+"] failed: "+status);
                }
                console.log( "bounds["+searchIndex+"] returns "+results.length+" results" );
                for (var i = 0, result; result = results[i]; i++) {
                    var marker = createMarker(result);
                    place_results.push(result.reference); // marker?
                }
                dfd.resolve(place_results, searchIndex+1);
            });
            return dfd.then(findNextPlaces);
        } else {
            return dfd.resolve(place_results).promise();
        }
    }

    return findNextPlaces([], 0);
};

$.search(boxes,0).then(function(results) {
    console.log("done", results);
}, function(err) {
    alert(err);
});