Andrew
Andrew

Reputation: 795

Callback on the function JS

I'm trying to make this work, what am I doing wrong?

I want to be able to do some stuff when function one is completed.

function one() {
    // do stuff
}

function main() {

    //script
    //script
    one(function() {
      // do some stuff when "one" is completed
      console.log("one is completed");
    });

} 

Why this doest fire a callback? (no log entry in the console)

Upvotes: 0

Views: 52

Answers (3)

Tristan De Oliveira
Tristan De Oliveira

Reputation: 808

You need to pass the callback as an argument and call it like normal function

function one(a, b, fn) {
    // do staff
    if (fn) {
      fn()
    }
}

function main() {

    //script
    //script
    one(5, 6, function() {
      // do some stuff when "one" is completed
      console.log("one is completed");
    }

} 

Upvotes: 3

Dave
Dave

Reputation: 2210

You need to pass the callback function inside the one() function. Then you need to call that function:

const one = (cb) => {
    console.log('in one()');
    cb();
}

const main = () => {
    one(() => {
        console.log('one() is completed');
    });
} 

main();

OUTPUT:

in one()
one() is completed

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138537

Cause one does not expect a callback, therefore it will be ignored and never called back.

function one(callback) { // <- take a callback
   callback(); // <- call back the callback "callback"
 }

Upvotes: 0

Related Questions