0

First of all, I completely read all the answers on this question, but despite that I come to realize that after years of scripting I ended up in the aSync hell.

I have a method that uses an async function. Depending on the result of that function, the method should return true or false.

So, simply said:

example = {
    overview: undefined,
    aSyncFunction: function (callback) {
        // Adds values to overview, which we will use in otherFunction
        callback();
        return this;
    },

otherFunction: function (data) {
    var result = false;

    this.aSyncFunction( function () {
        var available = this.overview[data.name];
        // result == filter overview with supplied data)
    }.bind(this));

    return result;
  }
};

I've created a JsFiddle to show you the exact situation I'm in: https://jsfiddle.net/copt436a/1/

Deleting the setTimeOut will deliver true, otherwise it is false.

Note, I'm cannot change aSyncFunction at the moment, so the solution must be somewhere in otherFunction

I tried to separate the callback function in a different function, but in that case the return value is stuck in that particular function otherFunction keeps returning undefined. Also using the return value of aSyncFunction does not give me the result I want, cause this returns this.

I'm completely stuck on this one, and probably the solution is quite simple.

Community
  • 1
  • 1
Sebass van Boxel
  • 2,514
  • 1
  • 22
  • 37
  • You could return a Promise that will be fulfilled when `aSyncFunction` has fired, and set a `then()`, or simply append the synchronous part following `otherFunction` in the `callback` – Kaiido Feb 23 '16 at 13:35
  • Forget to mention, no ES6. – Sebass van Boxel Feb 23 '16 at 14:07
  • Well the second part of my comment ("or simply ...") is ES5 and probably above compliant. It would become something like `otherFunction=function(data, callback){var result=false; this.asyncFunction(function(result){var available = this.overview[data.name]; callback(result)};` with `callback` being whatever you want to do with the result of the `asyncFunction` (`this.otherFunction(function(res){console.log(res)})` – Kaiido Feb 23 '16 at 14:29
  • 1
    https://jsfiddle.net/copt436a/2/ – Kaiido Feb 23 '16 at 14:37

0 Answers0