Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a function with parameters inside a callback

I've written a function which may take an unknown number of functions as parameters, but can't figure how I can make this work when one or more of the functions take parameters too.

Here is a quick 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);
like image 811
Ronan Avatar asked Dec 24 '22 18:12

Ronan


1 Answers

You can pass an anonymous function which can call the function with 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);
like image 172
Arun P Johny Avatar answered Dec 27 '22 20:12

Arun P Johny