Sharon Chai
Sharon Chai

Reputation: 517

passing multiple callback in a function

funcOne(cb) {
  //some async actions
  cb(resp) //pass resp to callback function
}



fucntionTwo(resp) { console.log(resp) }
fucntionThree(resp) { console.log(resp) }

funcOne(funcTwo)
funcOne(funcThree)

function one will run twice with above case, how can I make funcOne run once but trigger funcTwo and funcThree? I need to pass the resp from funcOne and execute funcTwo and funcThree Means passing multiple callback in funcOne.

I know I can pass multiple args but is there any other way to do that?

Upvotes: 3

Views: 13103

Answers (7)

Shuvro
Shuvro

Reputation: 242

You can follow this code, I hope your problem will be solved

function funcOne(fucntionTwo, fucntionThree) {

    fucntionTwo(resp)
    fucntionThree(resp)
}

funcOne(function (resp) {
    console.log(resp)
}, function (resp) {
        console.log(resp)
})

Upvotes: 0

AmerllicA
AmerllicA

Reputation: 32757

It's so easy:

function One(arg) {
    Two(arg);
    Three(arg);
}

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201537

You could use the rest parameter syntax and then use a forEach and apply the functions. Something like

function funcOne(...cb) {
        console.log("one");
        cb.forEach(s => s.apply());
}

function funcTwo() {
        console.log("two");
}

function funcThree() {
        console.log("three");
}

funcOne(funcTwo, funcThree);

and you can call funcOne with any number of function parameters.

Upvotes: 6

Vaibhav Patil
Vaibhav Patil

Reputation: 132

You can make use of arguments keyword.

Demo Example

function test()
{ for(var i=0; i< arguments.length; i++)
   arguments[i]();
}

test(fun1 , fun2)

Upvotes: 0

Faly
Faly

Reputation: 13356

You can pass the two callback into your functionOne:

funcOne(cb1, cb2) {
    cb1();
    cb2();
}

funcOne(funcTwo, funcThree);

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68443

Simply pass multiple arguments as callback functions

function funcOne(cb1, cb2) {
  cb1();
  cb2();
}

if number of callbacks are going to be dynamic then iterate arguments

function funcOne() {
  Array.from( arguments ).forEach( s => typeof s == "function" && s() );
}

and invoke it as

funcOne( function(){ console.log(1) }, function(){ console.log(2) }, function(){ console.log(3) } )

Upvotes: 2

void
void

Reputation: 36703

Pass two functions as arguments

funcOne(a, b) {
  a(); b();
}

funcOne(funcTwo, funcThree)

If the scope of the functions is the way you have mentioned then you do not need to even pass them as arguments. Just directly call them.

function funcOne() {
  //some async actions
  var resp = "Some response";
  fucntionTwo(resp);
  fucntionTwo(resp);
}

funcOne();

function fucntionTwo(resp) { console.log(resp) }
function fucntionThree(resp) { console.log(resp) }

Upvotes: 0

Related Questions