Search code examples
node.jscallbackreturnanonymous-function

How to return a variable from a callback?


I'm a newbie and now I'm having trouble returning a value from a callback function

function SumCallback(var1,var2,callback){
callback(var1+var2)
}

function Sum(var1,var2){
SumCallback(var1,var2,function(result){
console.log(result) //5
return result
})
}

console.log(Sum(3,2)) //undefined

How can I return the value in the correct way?


Solution

  • The execution looks like that

    |-> This calls "SumCallback"

    |--> This calls the "callback"

    |---> This calls console.log(result)

    |---> return "result"

    |--> return undefined

    |-> return undefined

    You only need to return the callback.

    function SumCallback(var1,var2,callback){
     return callback(var1+var2)
    }
    
    function Sum(var1,var2){
     return SumCallback(var1,var2,function(result){
      console.log(result) //5
      return result
     })
    }
    
    console.log(Sum(3,2)) //5
    

    The new execution looks like that

    |-> This calls "SumCallback"

    |--> This calls the "callback"

    |---> This calls console.log(result)

    |---> return "result"

    |--> return the value of the "callback" (result)

    |-> return the value of "SumCallback" (result)