0

myCallback() will be executed once the response is received and console.log(scope.mediafiles) returns undefined. I need to display scope.mediafiles.

foo = function(callback) {
  $http(method: "get", url: "http://myhost/bananas", options = {}).success(callback)}

myCallback = function(result) {
  scope.mediafiles = result
  console.log(scope.mediafiles) // it will output the result
}

foo(myCallback);

console.log(scope.mediafiles) // output undefined

@AlekseySolovey Even if I read the documentation, I still do not understand.

mydata.then(function(res){scope.mediafiles = res;});

returns

enter image description here

Thanks a lot for your Support!

Fabrizio Bertoglio
  • 5,890
  • 4
  • 16
  • 57
  • `.success` is deprecated use `.then` instead. – Master Po Apr 03 '18 at 12:59
  • `console.log(scope.mediafiles)` is _undefined_ because it is called **before** `myCallback`, since that one is asynchronous (where the data can arrive in few milliseconds or in several minutes). Keep your logic within the callback – Aleksey Solovey Apr 03 '18 at 13:01
  • @AlekseySolovey ok, that means doing everything inside `myCallback = function(result) { // my code logic }`. What If I need this data to be utilized in other functions? How can I get it out of the scope `function myCallback(result) { scope.mediafiles = result }` – Fabrizio Bertoglio Apr 03 '18 at 13:15
  • 1
    @FabrizioBertoglio return the data instead: `foo = (callback) => {return $http.get(url).then(callback);}` with `myCallback = (result) => {return result.data;}`. **Note** both `return` used for the Promise (`$http.get` request) and the response. Then you need to resolve the promise every time you need the data: `foo(myCallback).then((res) => {scope.mediafiles = res;})` – Aleksey Solovey Apr 03 '18 at 13:15
  • @AlekseySolovey thanks. in this case `mydata = foo(myCallback)` will return `Promise {$$state: {…}, success: ƒ, error: ƒ}`. I would need it to return the `response.data` – Fabrizio Bertoglio Apr 03 '18 at 13:26
  • 1
    @FabrizioBertoglio yup, that's a Promise that `$http` request returns, so just resolve it: `mydata.then(function(res){scope.mediafiles = res;});` – Aleksey Solovey Apr 03 '18 at 13:28

0 Answers0