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()。此小提琴上的代码/注释