Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用jquery在phonegap类上返回延迟对象?_Javascript_Jquery_Html_Cordova_Jquery Deferred - Fatal编程技术网

Javascript 如何使用jquery在phonegap类上返回延迟对象?

Javascript 如何使用jquery在phonegap类上返回延迟对象?,javascript,jquery,html,cordova,jquery-deferred,Javascript,Jquery,Html,Cordova,Jquery Deferred,我先举个例子: jQuery.when(setLocation()).then(function(e) { console.log(e); }); function setLocation(){ return navigator.geolocation.getCurrentPosition(setLcationSuccess, onGeoError); } function setLcationSuccess(position) { return position.c

我先举个例子:

jQuery.when(setLocation()).then(function(e) {
    console.log(e);
});

function setLocation(){
    return navigator.geolocation.getCurrentPosition(setLcationSuccess, onGeoError);
}

function setLcationSuccess(position) {
    return position.coords.latitude; // 33.5554444
}
在此示例中,
e
未定义。我需要获取
setLcationSuccess()
返回的任何内容

我需要用一个延迟的obj运行
setLocation()
,这样我就知道坐标何时准备好了

有什么想法吗?

试试看

jQuery.when(setLocation()).then(function(e) {
    console.log('a', e);
});

function setLocation(){
    var d = $.Deferred();
    navigator.geolocation.getCurrentPosition(function(position){
        d.resolveWith(this, [position.coords.latitude]);
    }, function(){
        d.reject();
    });
    return d.promise();
}

演示:

我对已接受的答案有改进建议。例如:不使用
$.when()
/
.then()
,您可能应该始终使用
.resolveWith()
/
.rejectWith()
.resolve()
/
.reject()。此小提琴上的代码/注释