ios5preferencestrigger.io

return an undefined value with forge.prefs


I try to use the module PREFS but I don't know why it returns me an undefined value

function getId() {
    var id=0;

    forge.prefs.get("user_id", function(value){
        id=value;
        forge.logging.info("entry  id " +id);      
    });

    return id;  
};

OUTPUT : when I call this method it returns me 0 !!! and the log with "entry id 37"

I don't know why the value of id do not change after call this method.


Solution

  • i found the solution from Patrick Rudolph forge.prefs.get() is probably an asynchronous function call, which means that its callback is executed somewhat delayed. In your example load_my_car() is executed before the two callbacks are fired, so the variables are still undefined.

    You have to make sure that the callbacks are fired before calling load_my_car(), try this:

    forge.prefs.get('offset_val' function(offset1){
      forge.prefs.get('id', function(val){
        load_my_car(val,offset1);
      }); 
    })
    

    ; If you really don't want to have two nested forge.prefs.get() you'd need to check which callback finishes first and then only call load_my_car() after the second finished.