简体   繁体   中英

Function callback in pure JS

We can do like this in jquery, but I never understand how it work in native JS.

function init(){

 return $.ajax({
 'type':POST,
 'url':'example.com'

})

init.success(function(data){
data
});

How can we write a callback in pure JS? so that I can use it this way :

myFunction('myparam',function(){
return 'this is myFunction callback';
}

In Javascript, a function can be passed to another function like every other argument. That functions can later use it, by invoking it whenever it needs. This is very common for callback functions.

Example:

function checkName(name, callbackFn){
  if(name == "Alice"){
    callbackFn("Great Name!");
  }
  else {
    callbackFn("Wrong name");
  }
}

And the call can be:

checkName("Alice", function(message){
  alert(message);
});

This kind of programming is very useful for asynchronous tasks (like Ajax calls), since the handling function can invoke the callback function when the task is done.

Using callback functions is a method related to functional programming, where functions are passed between higher level functions as arguments. Another way to achieve this goal in the new JS spec (ES2015), is using Promises , which can be resolved only when the task is done.

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