简体   繁体   中英

Why does the callback() function needed to be run in order for the callback function to work?

I am learning callback right now and there is not so much of helpful posts there. I wanted to know why the callback() needed to be run in order for the function to work? Code:

<script>
function createQuote(quote, callback){
alert(quote);
callback();
}
createQuote('I am Toby ', function(){
alert("Last");
});
</script>

What would be the difference if the callback isn't run? Would provide the same result? Any help will be apreciated.

Well in this case you just pass the callback function to the createQuote function. CreateQuote doesnt know what to do with the callback or when to do it so you have to tell it to run it yourself.

How would createQuote know when to call the callback otherwise? You may have a lot of code before that call to supply the callback with data.

Callbacks need to be run just like how values that you input need to be used. if you don't use the variable quote , then that is useless, same with callbacks, if you don't call the callback, nothing happens and the code doesn't run.

callbacks are useful for example when you want to do something, and run the code after that thing has been done, and you have to call the callback there in the function to know when and where to run the code inside the function

the code inside functions is not ran when you declare them but only when you call the function. When you pass in a function as a callback, you don't call the function, but just pass in the name

examples:

function callFunction(callback){
    console.log("doing stuff")
    callback()    //runs the function you pass in
    console.log("after callback")
}

function sayHello(){
    console.log("hello")
}

callFunction(sayHello) // not callFunction(sayHello())
//prints in the console:
//doing stuff
//hello
//after callback

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM