1

I've been messing around with callbacks all day & I can't seem to figure out how to call info out of callback. Im using request.js, & I read that there is a callback property but I don't know how to apply it, any input would be appreciated. Here is the code

function add(i, call) {

  var options = {
    url: 'Hidden' + i,
    headers: {
      'Authorization': 'Token token="Hidden"'
    }
  }

  function callback(error, response, body) {
    var info = JSON.stringify(JSON.parse(body), null, 1);
    console.log(info);    
  }

  request(options, callback);
  call(info);
}

function apply(data) {
  console.log(data)
}

add(1, apply);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
MGomeyy
  • 215
  • 1
  • 2
  • 8
  • So could you explain what error's / problem's your getting.? – Keith Nov 07 '16 at 22:26
  • @Keith the properties for request require `callback(error, response, body)` so I'm not suite sure how to apply a callback in order to get the variable inside the function, after `request(options, callback);` has run – MGomeyy Nov 07 '16 at 22:28
  • Still not sure what your problem is, request is an async function.. If do you mean after you call add you want it to return the value,.. Then you can't do it that way.. You would need to add a callback to your add function.. But better than that you might want to look into using Promises, as it's very easy to get caught in callback hell when dealing with async functions. – Keith Nov 07 '16 at 22:32
  • I've added a callback to my add function, & I still wasn't able to access it. I did `function add(i =1, call)` & in the add function I called `call(info);` & wasn't able to access the value. Am I doing that right – MGomeyy Nov 07 '16 at 22:35
  • *"I've added a callback to my add function, & I still wasn't able to access it."* Please post your code. You might want to have a look at [How do I return the response from an asynchronous call?](http://stackoverflow.com/q/14220321/218196) – Felix Kling Nov 07 '16 at 22:38
  • If you call it like -> `add(1, function (info) { console.log(info); });` should work. Again, you might want to look into promises, as callbacks can become very unmanageable. – Keith Nov 07 '16 at 22:39
  • @FelixKling Updated my code – MGomeyy Nov 07 '16 at 22:43
  • `info` only exists **inside** `callback`, but you placed `call(info)` **outside** of `callback`. That also means `call(info)` is executed before `callback` is executed. That cannot work. Move `call(info)` **inside** `callback`. I recommend to read a JavaScript tutorial that explains scope, e.g. http://eloquentjavascript.net/03_functions.html#h_u4j2OhpYkg . – Felix Kling Nov 07 '16 at 22:44
  • @FelixKling I've moved `call(info)` inside of `callback` & its still not logging anything – MGomeyy Nov 07 '16 at 22:53
  • If you don't even see the `console.log(info);` part, then the issue is somewhere else. – Felix Kling Nov 07 '16 at 22:55

0 Answers0