Use function with parameters inside callback

I wrote a function that can take an unknown number of functions as parameters, but cannot figure out how I can do this when one or more functions also take parameters.

Here is a brief example of what I would like to achieve:

function talk(name) {
  console.log('My name is ' + name);
  var callbacks = [].slice.call(arguments, 1);
  callbacks.forEach(function(callback) {
    callback();
  });
}

function hello() {
  console.log('Hello guys');
}

function weather(meteo) {
  console.log('The weather is ' + meteo);
}

function goodbye() {
  console.log('Goodbye');
}

// I would like to be able to do the following:
//talk('John', hello, weather('sunny'), goodbye);
+4
source share
2 answers

You can pass an anonymous function that can call a function with the required parameters

talk('John', hello, function(){
    weather('sunny')
}, goodbye);

function talk(name) {
  console.log('My name is ' + name);
  var callbacks = [].slice.call(arguments, 1);
  callbacks.forEach(function(callback) {
    callback();
  });
}

function hello() {
  console.log('Hello guys');
}

function weather(meteo) {
  console.log('The weather is ' + meteo);
}

function goodbye() {
  console.log('Goodbye');
}

talk('John', hello, function() {
  weather('sunny')
}, goodbye);
Run codeHide result
+8
source
talk('John', hello, weather.bind(null, 'sunny'), goodbye);

In this case .bind, it essentially returns a function with some associated parameters - completely analogous to Arun's answer, although you may consider this method a bit more concise / readable.

+2
source

All Articles