1

I want to do an API request and display the body in a table on my site. I'm using Node.JS, React and Request. This is my code:

var requestResult = Request.get('https://test.ipdb.io/api/v1/assets/?search=asdf', (err, res, body) => {
  return body;
});

This is obviously not working. I can console.log(body), but I want the API response to be available outside the callback function. Is that possible?

Lazyexpert
  • 3,106
  • 1
  • 19
  • 33
shnoop
  • 81
  • 1
  • 7
  • Callbacks are not meant to return a value. Returning a value is more of a synchronous way of writing the code. In a callback, a value needs to be set and then the next function is invoked. – Jay Jul 19 '17 at 07:47

1 Answers1

2

If you're using callbacks approach, then you should continue your job in callback function.
Example:

app.get('/', function(req, res, next) {
  Request.get('https://test.ipdb.io/api/v1/assets/?search=asdf', (err, res, body) => {
    console.log(body);
    // do any other job here
    res.send(body);
  });
});

Other approaches you can use in 2017:

  • promises
  • coroutines + generators
  • async + await

You can gain more info here.

Lazyexpert
  • 3,106
  • 1
  • 19
  • 33