In my Cordova android app i am using getDeviceId
function to get the unique device 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;
}
And i am calling this function like this way
var deviceId=getDeviceId();
//undefined error
alert("from function"+deviceId);
I will get device-id successfully inside the function,but the return value will give undefined error.
Use promise!
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);
}
and then
getDeviceId(function(uuid){
console.log(uuid); //this might be object, so drill to specific field
alert("from function" + uuid);
}, function(errorMessage){
alert(errorMessage);
});
Checkout greate article about promises in details
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.