0

I need to return value from my getItemData function, like this :

function getItemData(success, error) {
    var clientContext = new SP.ClientContext.get_current();
    var ListeEtabScol = clientContext.get_web().get_lists().getByTitle('Etablissements Scolaires');
    var ItemEtabScol = ListeEtabScol.getItemById(123456);

    clientContext.load(ItemEtabScol, 'Title', 'Adresse', 'Commune');
    clientContext.executeQueryAsync(
        function() { success(ItemEtabScol); }, error
    );
}

var test = getItemData(
    function(item){
        return item.get_item('Adresse'); //this is ok, adress is returned
    },
    function(sender, args){
        alert('Erreur : ' + args.get_message());
    }
);

console.log(test); //test is undefined :-( what's wrong ???

but my test variable is ever undefined. Any idea of my mistake ?

Thanks in advance!

  • 4
    Possible duplicate of [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – Carcigenicate Feb 27 '18 at 12:58
  • 1
    That link is partially relevent, but you never return anything from the function anyways. You'll need to return a Promise of a value or something – Carcigenicate Feb 27 '18 at 12:58
  • 1
    @RickRiggs That won't help anything. – Carcigenicate Feb 27 '18 at 12:59
  • 1
    you **can not** return a value from some async code, because you have no idea wether/when some value is available. Check out the link in the first comment and/or Promises. – Thomas Feb 27 '18 at 13:02
  • I'm sorry, but I tried jquery's deferred function and Promise with then() without success :-( That's why I want to use callbacks... any help please ? – Florent Bignier Feb 27 '18 at 13:44

1 Answers1

0

Question has already been asked and answered many times...

How to return value from an asynchronous callback function? (concise)

How do I return the response from an asynchronous call? (detailed)

Simply put, you need to use a callback (a function that will be "called back" when what you asked for is completed):

function onComplete(a){ // When the code completes, do this
    console.log(a);
}

function getFive(callback){ 
    var a;
    setTimeout(function(){ //just here to have asynchronicity
         a=5;
         callback(a); 
    },10);
}

and usage would be:

getFive(onComplete);

Answer taken from https://stackoverflow.com/a/6847754/9368855

Blustch
  • 1
  • 3