简体   繁体   中英

Is this an example of javascript callback function?

I only want to know if this can be an example of javascript callback function:

function doing_stuff(str,callback) //external *asynchronous* function
    {
    if(confirm(str)) callback(true);
    else callback(false);
    }

function main_func() //main function
{
var to_be_sent='NONE'; //return value set with default

var callback = function callback(r) //funzione di callback
{
to_be_sent=r;
}

doing_stuff('Sure?',callback); //external function call with *callback*

return to_be_sent;
}

You don't seem to understand the concept of a callback.

In computer programming, a callback is a piece of executable code that is passed as an argument to other code , which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback , or it might happen at a later time as in an asynchronous callback .

In Javascript, "a piece of executable code" can be wrapped inside a function . Functions in javascript are First-Class Citizens , which means you can treat them like any other value, executing operations over and passing them as parameters.

Meanwhile callbacks can be synchronous, they make more sense when are called asynchronously . Basically you are saying:

Hey dude, do your thing, take your time, but whenever you finish processing, please execute this piece of code.


So, answering your question:

YES, you have an example of callback usage.

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