0

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)

3 Answers 3

3

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");
    }

} 
Sign up to request clarification or add additional context in comments.

5 Comments

Ok, what if I do not need the callback every time I call this function?
Check my edit, you can just add a condition if the callback exist
Ok, I don't need to change anything in the 'main' func, this is correct? If I need to pass some parameter(s) to 'one' func, besides the callback, how do I do that?
Edited,, Because the callback is same as un argument you can just add arguments in the declaration before or after the callback
Thank you @Tristan De oliveira
0

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"
 }

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.