Click here to Skip to main content
15,895,772 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi ,

Why am i getting the following error:*ReferenceError: result is not defined"*

What I have tried:

JavaScript
function returnData(){
    
    _myService.getData().then(function(data){
      
      var result = data;
    })

return result;
}
Posted
Updated 4-Apr-17 6:28am
v3
Comments
F-ES Sitecore 4-Apr-17 11:27am    
I don't see how that code can give you that error. I'm going to assume you are using "result" elsewhere like

returnData();
var x = result.someProperty;
1Future 4-Apr-17 11:29am    
sorry .. i just updated the question ..return result instead of return data

1 solution

The getData function returns a Promise - something which will produce a result at some point in the future.

Promises[^]
JavaScript Promises ... In Wicked Detail - Matt Greer[^]

The function you pass to then will not be executed until the result has been produced. That will be at some point after your returnData function has returned.

You can't return the result of an asynchronous operation before that operation has completed. You'll need to change your function to return the promise instead, and then move the code that uses the result of the function into a callback:
JavaScript
function returnData(){
    return _myService.getData();
};

...

returnData().then(function(data){
    // Do something with the data here...
});
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900