简体   繁体   中英

Chaining functions without callbacks

I have a function deviceUpdate(ID, Token) that I can call to update the list of devices for the user. This function does an ajax call where it displays a loading image until it is finished then displays all the info.

There is one particular time I would like to perform an additional (anonymous) function after the update is finished. How can I do this without embedding the anonymous function inside the deviceUpdate function?

As @Joachim Isaksson suggested, it can be passed in as a parameter.

Example:

function deviceUpdate(ID, Token,callback){
 $.post('url',data,function(response){ //ajax with jQuery post as example
   // your processing of response
    'function' === typeof callback && callback(); // if a function was passed in, run it!
 });
}


deviceUpdate(ID, Token); // for normal use

deviceUpdate(ID, Token,function(){
   // this is the anonymous function to be run in the special case 
});

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