在我的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,但返回值将给出未定义的错误。
答案 0 :(得分:2)
使用承诺!
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);
});
Checkout会更新有关promises in details
的文章