如何在自定义函数中使用jQuery Promise/Deffered? [英] How do I use jQuery promise/deffered in a custom function?

查看:91
本文介绍了如何在自定义函数中使用jQuery Promise/Deffered?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过navigator.geolocation获取位置的函数:

I have a function that gets the location through navigator.geolocation:

var getLocation = function( callback ){

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

        // Stuff with geolocation

    });

};

我想做到这一点,以便可以使用jQuerys的 Deffered 对象,但我仍然没有掌握Deffered的概念和用法.

I would like to make it so that I could chain this function using jQuerys' Deffered object but I have still not managed to grasp the concept and usage of Deffered.

我正在寻找与此伪代码类似的东西:

I'm looking for something similar to this Pseudo Code:

getLocation().then(function(){
    drawMarkerOnMap();
});

在不向后翻转和淹没代码的情况下,这种语法是否还可能实现?

Is this syntax even possible without flipping over backwards and drowning in code?

推荐答案

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

You have to instantiate a new deferred object and return it (or its promise) from the function. Call its .resolve method once you get the response:

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

用法:

getLocation().then(drawMarkerOnMap);


参考: jQuery.Deferred


Reference: jQuery.Deferred

附录:

我建议不要使用两种方法,即延迟对象和将回调传递给函数,以保持接口简单.但是,如果必须保持向后兼容,则只需在递归对象上注册传递的回调:

I would advise against using both approaches, deferred objects and passing callbacks to the function, to keep the interface simple. But if you have to stay backwards compatible, you can simply register the passed callback at the deferred object:

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

这篇关于如何在自定义函数中使用jQuery Promise/Deffered?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆