简体   繁体   中英

Wait for function to finish execution

I have the following:

function functionA() {
    var myVar = functionB();
    functionC(myVar);
}

the time, functionB needs to answer, depends on user input. It may be 1s, but also 10s. So functionC always is called with an undefined value, because functionB() hasnt't finished yet. So I tried this:

function functionA() {
    var def = $.Deferred();
    var myVar = functionB();
    def.resolve();
    $.when(def).done(function () {
        functionC(myVar);
    });
}

This also doens't work. I saw this on StackOverflow: javascript function wait until another function to finish But how can it be transferred to my problem? To recap, execution of functionA needs to stop, until functionB() has answered. Thanks.

You can change functionB to return the deferred object, which you can then resolve within the async handler, something like this:

function functionA() {
    var deferred = functionB();
    $.when(deferred).done(functionC);
}

function functionB() {
    var deferred = $.Deferred();

    // do something async here...
    // asyncCallback() { 
    //     deferred.resolveWith(this, dataRetrieved);   
    // }

    return deferred;
}

function functionC(data) {
    console.log(data);
}

Putting your example in a simple object, you can do the following:

var myObject = {
    myProp: null,
    functionA: function () {
        this.functionB();
        var self = this;
        var i = setInterval(function () {
            if (self.myProp) {
                clearInterval(i);
                self.functionC();
            }
        }, 100);
    },
    functionB: function () {
        // ...
        this.myProp = 'user input';
    },
    functionC: function () {
        // ...
    }
};
myObject.functionA();

The script will check every 0.1s if myProp is set. If so, the interval is cleared and functionC is called.

No jQuery needed in this case.

You can pass functionC as a parameter to your functionB as mention here .

function functionA() {
   var myVar = functionB(callback);
   functionC(myVar);
}

function functionB(callback) {
   // does something ...
   if(callback && typeof(callback) === "function") {
      callback();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM