-2

How can I pass a variable back to the callback function. Like for example if a api call finished, I want to return its data back to the function of the callback.

I want to archieve this (how do I pass the data variable?):

MyObject.DoItWithThis(function(***data***) {
     console.log(data) 
}

settings the callback --> API request starts --> API request finishes --> call the callback with the result.

tomwassing
  • 925
  • 1
  • 10
  • 30
  • Where is your code for `MyObject.DontWithThis()`? – nnnnnn Feb 26 '17 at 23:29
  • http://stackoverflow.com/questions/3458553/javascript-passing-parameters-to-a-callback-function – Ousmane D. Feb 26 '17 at 23:29
  • @OusmaneDiaw I saw that question. I want to receive a variable in the function not passing it. – tomwassing Feb 26 '17 at 23:31
  • You might want to take a look at Promises, so Instead of "passing back" the result of the callback to the calling function, you can chain the callbacks. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise – Daniel Ormeño Feb 26 '17 at 23:32
  • You don't have to do anything. `data` will be in scope and visible to the callback. `MyObject.DontWithThis(function() { console.log(data); });` – Raymond Chen Feb 26 '17 at 23:33
  • @tom12e If the callback should receive the value in its `data` parameter, then `DontWithThis` needs to pass the value to the callback invocation. Please show us your full code and tell us what exactly does not work as expected. – Bergi Feb 26 '17 at 23:34

2 Answers2

0

The easiest way, if you only need one piece to be passed back, is to return that value from the function.

However, your calling code must be aware of that return type and use it in order to make it work.

function callee( data ){
   if (data == null)
      return false;
   doStuffWith( data );
   return true;
}

function caller( callback ){
    var nonNull = "abc";
    if (callback( nonNull )){
        doSomeOtherStuff();
    }
}

caller( callee );
Psi
  • 6,387
  • 3
  • 16
  • 26
0

I have solved it in the following way with ES6:

Watch it in action: http://codepen.io/anon/pen/vxOGve

class Test {
    constructor() {
        this.callback = function (data) {
            console.log(data)
        };
        for (var i = 0; i < 50; i++)
            if (this.callback && typeof this.callback === "function") {
                this.callback("lol");
            }
    }

    // for example
    set Callback(callback) {
        this.callback = callback;
    }
}

var test = new Test();
tomwassing
  • 925
  • 1
  • 10
  • 30