admin管理员组

文章数量:1356815

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);

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);
Share Improve this question edited Apr 4, 2016 at 11:23 Priya 1,3516 gold badges21 silver badges41 bronze badges asked Apr 4, 2016 at 10:58 zm455zm455 4991 gold badge11 silver badges26 bronze badges 2
  • You can get it in the callback – Rayon Commented Apr 4, 2016 at 10:59
  • function foo(myCallback) { } function bar(cb) { foo(function() { var result = "hello"; cb(result); }); } bar(function(res) { alert(res); }); – Rayon Commented Apr 4, 2016 at 11:02
Add a ment  | 

3 Answers 3

Reset to default 6

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);
});

本文标签: callbackjavascript returning value from anonymous functionStack Overflow