-1

My friend and I have been struggling with Node.js callbacks since yesterday. We have the following function:

// helperFunction.js
function foo(param) {
    request.get({
        url: <url>
        headers: {<headers>}
    }, (err, response, data) => {
        array = []
        obj.forEach(function (entry) {
               // do stuff with array
            };            
        });
        return array;
    });
}
module.exports.foobar = foo;

then we call that from our app.js. Since yesterday, we have updated the code to wait for the callback by using a function, like so:

// app.js

//var bar = require('./helperFunction');
//console.log(helperFunction.foobar('param')); // prints undefined

function bar(){
    console.log('Log something')
}
foo(bar);

but we don't know how to pass the parameter to foo. I tried to add param (which is a string) to bar but it doesn't work.

For the record, I'm aware of other posts such as this, but I cannot make it work on my code.

2 Answers2

0

Pass a function to foo. Something like:

foo(() => bar("Hi, I'm something"));

function foo(fn, err) {
  if (!err && fn instanceof Function) {
    fn();
  }
}

function bar(someThing){
  console.log(`Log ${someThing}`);
}
KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

In foo you just add a callback parameter and instead of returning you call this function. As a convention, the first parameter of the callback function is the error object. If no error occurred, this object is null and the following parameters are the actual result of the function. Your code didn't include error handling so I added it. If error exists you won't receive any data and foo can't calculate whatever it tries to calculate. In this case, foo should either try to solve the problem itself or propagate the error to its caller.

function foo(param, cb) {
  request.get({
      url: <url>
      headers: {<headers>}
  }, (err, response, data) => {
      if (err) {
          return cb(err);
      }
      array = []
      obj.forEach(function (entry) {
             // do stuff with array
          };            
      });
      cb(null, array);
  });
}

function bar(err, data){
    console.log('Log something')
}

foo('some param', bar);
Josh
  • 649
  • 1
  • 5
  • 13