问题描述
在我的Cordova android应用程序中,我正在使用getDeviceId
函数来获取唯一的设备ID。
function getDeviceId(){
var temp;
newid=cordova.require('org.apache.cordova.uuid.UniqueDeviceID');
newid.getDeviceID(success,fail);
function success(uuid){
//this works
alert("inside function"+uuid);
temp=uuid;
}
function fail(err){
// alert("error"+err);
}
return temp;
}
我以这种方式调用此功能
var deviceId=getDeviceId();
//undefined error
alert("from function"+deviceId);
我将在函数内成功获取device-id,但返回值将给出未定义的错误。
1楼
Medet Tleukabiluly
2
已采纳
2015-07-31 05:39:44
用诺!
简短答案:
function getDeviceId(success, fail){
return cordova.require('org.apache.cordova.uuid.UniqueDeviceID').getDeviceID(success, fail);
}
更好的答案:
function getDeviceId(){
var temp; //assume this as cache, this must be outside of this function scope, but for the sake of example
var defer = q.defer(); //or any other promise libraries
if(!temp){
var cordova = cordova.require('org.apache.cordova.uuid.UniqueDeviceID');
cordova.getDeviceID(function(uuid){
temp = uuid;
defer.resolve(uuid); //or other api depend on library
}, function(err){
temp = null; //clear cache on errors
defer.reject('Could not get device id');
});
} else {
defer.resolve(temp);
}
return defer.promise; //or other api depend on library
}
给您的具体答案:
function getDeviceId(success, fail){
return cordova.require('org.apache.cordova.uuid.UniqueDeviceID').getDeviceID(success, fail);
}
接着
getDeviceId(function(uuid){
console.log(uuid); //this might be object, so drill to specific field
alert("from function" + uuid);
}, function(errorMessage){
alert(errorMessage);
});
忠告:
结帐有关