简体   繁体   中英

javascript: returning value from anonymous function

How can I get the value of var result in this code?

I know this is a basic problem but I'm looking for the solution since 3 days. Can you give me any suggestion please?

function foo(myCallback){
}

function bar() {
    var result = foo(function(){
        var result = "hello"; 
        return result;
    });
}

var showResult = bar();
alert(showResult);

You need to call the callback and return the value of it and inside your bar function, you need to return the result as well

 function foo(myCallback){ // return the value of the call myCallback() return myCallback(); } function bar(){ var result = foo(function(){ var result = "hello"; return result; }); // return the result return result; } var showResult = bar(); alert(showResult); 

A bit simplified it could be

 function foo(myCallback){ return myCallback(); } function bar(){ return foo(function(){ return "hello"; }); } var showResult = bar(); alert(showResult); 

You are missing the return statements. It isn't clear what you want to return.

It works like this:

function foo(myCallback){
  return myCallback();
}

function bar(){
    var result = foo(function(){
        var result = "hello"; 
        return result;
    });
  return result;
}
var showResult = bar();
alert(showResult);

You are stuck using callbacks, but fortunately you can pass parameters in your callback functions:

// define your functions
function foo(myCallback){
    myCallback();
}

function bar(callback){
    var result = foo(function(){
        var result = "hello"; 
        callback(result);
    });
}

// now run it
bar(function(showResult){
    alert(showResult);
});

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