0

I'm trying to create a callback function, but keep getting told that data is not a function. I've set it up according to another question, but does not seem to work?

getRequest("http://", function(error, data){
  console.log(data);
});

function getRequest(url, error, data) {
  request({
      method: 'GET',
      uri: url,
      headers: {
        'Content-Type': 'application/json',
        'dataType': 'json'}
    }, function (error, response, body){
      if(!error && response.statusCode == 200){

        data(JSON.parse(body));

      } else {
        error(error);
      }
    })
}
3
  • 1
    You are calling getRequest with two params. so the third data param is undefined. Commented Sep 5, 2016 at 11:20
  • i see, but how should it then look like in this case? Commented Sep 5, 2016 at 11:28
  • You might want to consider using a promise library like Bluebird to keep your callbacks under control. Chaining then(...) is often a lot easier than matching up function calls. Commented Sep 5, 2016 at 12:04

1 Answer 1

1

In case if you want to proceed both, success and failure result in one callback you should replace calling data with cb(or error as was in your code.

getRequest("http://", function(error, data){
  if(error) throw error
  console.log(data)
});

function getRequest(url, cb, data) {
  request({
      method: 'GET',
      uri: url,
      headers: {
        'Content-Type': 'application/json',
        'dataType': 'json'}
    }, function (error, response, body){
      if(cb) {
          cb(error, JSON.parse(body))
      }
    })
}

Otherwise, you should check if both callbacks provided

function getRequest(url, success, error) {
  request({
      method: 'GET',
      uri: url,
      headers: {
        'Content-Type': 'application/json',
        'dataType': 'json'}
    }, function (error, response, body){
      if(error && failure) {
         failure(error)
      } else if(success) {
         success(JSON.parse(body))
      }
    })
}

In this case, you should provide two callback functions, first for success result and a second one for error which is less common pattern.

Sign up to request clarification or add additional context in comments.

3 Comments

Using a single callback of the form function(error, body) is more consistent here.
@tadman, you're absolutely right, I've added a remark about that but I'm not sure if it fits OP needs so just in case provided another option.
Node.js is pretty adamant about keeping things consistent that way and while I thought it was strange when I started with it, that habit does keep your code a lot more orderly. The wild-west approach from before with dozens of contradictory callback methods is fading into history.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.