Reputation: 255
Why am i getting the following error:ReferenceError: result is not defined"
function returnData() {
_myService.getData().then(function(data) {
var result = data;
});
return result;
}
Upvotes: 0
Views: 93
Reputation: 19070
I suppose that calling _myService.getData()
you are making an Asynchronous call to a web service..
In that case you can return your service response data like this:
function returnData() {
return _myService
.getData()
.then(function(data) {
// Here you can work with the response data
return data;
});
}
Notice that you can work with the response
in the callback, as you correctly passed into then
.
Upvotes: 0
Reputation: 19
@Yosvel's answer is correct, the reason is because you are making an Asynchronous call to your service.
In doing so, you must wait for a result to be returned to you, which can then be processed in your then function.
By having two return calls, your return value is undefined because it is not waiting for the callback function, but simply returning a null value.
Upvotes: 0
Reputation: 1074495
Because result
is declared within the callback you passed into then
. It doesn't exist outside.
You can declare it outside, but note that it won't have the data as of your return result;
line later:
function returnData(){
var result; // <==== Note
_myService.getData().then(function(data){
result = data; // <==== No `var` here
})
// WON'T HAVE THE VALUE HERE, it's too soon
return result;
}
See How do I return the response from an asynchronous call? for why, and what to do about it. Basically, you don't need the returnData
function at all, it doesn't add any value (other than perhaps encapsulation around _myService
). It cannot return
the value. So either use _myService
directly, or if you're trying to hide that, just
function returnData() {
return _myService.getData();
}
...and use then
in the calling code to receive it. Since again, returnData
can't return
the data.
Upvotes: 2