0

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.

1 Answer 1

2

Use promise!

Short answer:

function getDeviceId(success, fail){
    return cordova.require('org.apache.cordova.uuid.UniqueDeviceID').getDeviceID(success, fail);
}

Better answer:

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   
}

Specific answer to you:

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);
});

Advice:

Checkout greate article about promises in details

Sign up to request clarification or add additional context in comments.

4 Comments

no, you are returning var temp which is undefined, it will be defined when success callback called, but that temp returned immediately, so obviously it will be always undefined
you need to pass function to var deviceId=getDeviceId();
Your specfic answer work partially but the temp variable returns undefined error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.