0

as mentioned above i have an issue getting the data out of the scope, which i set in the scope before in an asynchronous callback function.

Here is some of my Code:

var TransactionCtrl = require("controller/transactions.controller");

var onSuccess = function(_response) {
    this.showData = _response;
};

var TransactionsFunction = function() {
    //preparing asynchronous call
    var transactionCtrlInstance = new TransactionCtrl(onSuccess.bind(this));

    //firing asynchronous call      
    transactionCtrlInstance.getTransactions();
};

TransactionsFunction.prototype.run = function() {
    //show this.showData
    console.warn(this);
    console.warn(this.showData);
};

module.exports = TransactionsFunction;

Important to mention is, that i call the "run" function definitely after the asynchronous call returned, so the data should be applied in the scope.

Does somebody have an explanation or a workaround for this? Does the scope behave different in a callback function even if i bind the scope on it?

J Polack
  • 118
  • 1
  • 1
  • 5
  • `getTransactions()` need to either accept a callback or return a promise. Then you need to call `run()` using that callback (or the callback to the promise's `.then()`) – slebetman Aug 19 '15 at 08:16

1 Answers1

0

Calling the run method on new TransactionsFunction() will not guarantee that the async call had been completed. The new TransactionsFunction() would fire the asysnc call and then exit. If you call run() the async call may still have not been returned.

The only place you can ensure that the data has been returned is the onSuccess () method.

Your can check out incorporating such behavior using Promises.

jozzy
  • 2,863
  • 3
  • 15
  • 12
  • But if i write `setInterval(function(){ console.warn(this); }.bind(this), 50);` in the `run` Function the `this.showData` variable appears neither. Is `onSuccess()` really the only way to access the new variables? – J Polack Aug 19 '15 at 08:22