如何在自定义函数中使用jQuery promise/deffered?

hit*_*uct 33 javascript jquery jquery-deferred

我有一个功能,通过navigator.geolocation以下方式获取位置:

var getLocation = function( callback ){

    navigator.geolocation.getCurrentPosition( callback || function( position ){

        // Stuff with geolocation

    });

};
Run Code Online (Sandbox Code Playgroud)

我想使它这样我就可以用链jQuerys'这个功能递延对象,但我仍然没有成功地把握递延的概念和使用方法.

我正在寻找类似于这个伪代码的东西:

getLocation().then(function(){
    drawMarkerOnMap();
});
Run Code Online (Sandbox Code Playgroud)

这种语法是否可以在不向后翻转并在代码中淹没的情况下实现?

Fel*_*ing 61

您必须实例化一个新的延迟对象并从该函数返回它(或它的promise)..resolve获得响应后调用其方法:

var getLocation = function() {
    var deferred = new $.Deferred();

    navigator.geolocation.getCurrentPosition(function( position ){
        // Stuff with geolocation
        deferred.resolve(position);
    });

    // return promise so that outside code cannot reject/resolve the deferred
    return deferred.promise();
};
Run Code Online (Sandbox Code Playgroud)

用法:

getLocation().then(drawMarkerOnMap);
Run Code Online (Sandbox Code Playgroud)

参考:jQuery.Deferred


附录:

我建议不要使用两种方法,延迟对象和将回调传递给函数,以保持界面简单.但是如果你必须保持向后兼容,你可以简单地在延迟对象上注册传递的回调:

var getLocation = function(callback) {
    var deferred = new $.Deferred();

    if ($.isFunction(callback)) {
        deferred.then(callback);
    }

    navigator.geolocation.getCurrentPosition(function( position ){
        // Stuff with geolocation
        deferred.resolve(position);
    });

    // return promise so that outside code cannot reject/resolve the deferred
    return deferred.promise();
};
Run Code Online (Sandbox Code Playgroud)

  • @hitautodestruct:不,我的意思是让`getLocation`接受一个回调*并*返回一个延迟对象.即,有两种方式,无论是`foo(bar)`还是`foo().然后是(bar)`.只应该有一种方法来调用该函数. (2认同)