Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing anonymous function as callback in Javascript

Is there a way to pass anonymous function as a custom callback function in Javascript? I have this code:

function notifyme(msg){
    console.log(msg)
}

notifyme("msg", function(){
    //do some custom redirect logic    
});

I am trying the above code and it's executing notifyme function, but not going further with redirect code. I know I can pass a function name as a callback, but I don't have a specific function that I can pass. This is why they invented the anonymous function I guess.

It'd be really nice if there was a way to do that.

like image 481
Lamar Avatar asked Feb 13 '17 12:02

Lamar


People also ask

Can you use an anonymous function in a callback?

In JavaScript, callbacks and anonymous functions can be used interchangeably.

Can you pass a anonymous function as an argument to another function in JavaScript?

As JavaScript supports Higher-Order Functions, we can also pass anonymous functions as parameters into another function. Example 3: In this example, we pass an anonymous function as a callback function to the setTimeout() method.

How do you pass a callback function in JavaScript?

Passing a function to another function or passing a function inside another function is known as a Callback Function. Syntax: function geekOne(z) { alert(z); } function geekTwo(a, callback) { callback(a); } prevfn(2, newfn); Above is an example of a callback variable in JavaScript function.

Can we assign anonymous function in JavaScript?

An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.


1 Answers

Your code pattern should be like

function notifyme(msg,callback){
    console.log(msg);
    // Do your stuff here
    if(callback){
      callback();
    }
}

notifyme("msg", function(){
    //do some custom redirect logic    
});
like image 66
ricky Avatar answered Oct 01 '22 11:10

ricky