简体   繁体   English

等待函数完成执行

[英]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. functionB需要回答的时间取决于用户输入。 It may be 1s, but also 10s. 可能是1s,也可能是10s。 So functionC always is called with an undefined value, because functionB() hasnt't finished yet. 所以functionC总是用未定义的值来调用,因为functionB()尚未完成。 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? 我在StackOverflow上看到了这一点: javascript函数等待另一个函数完成,但是如何将其转移到我的问题上呢? To recap, execution of functionA needs to stop, until functionB() has answered. 概括地说,功能A的执行需要停止,直到功能B()应答为止。 Thanks. 谢谢。

You can change functionB to return the deferred object, which you can then resolve within the async handler, something like this: 您可以更改functionB以返回延迟的对象,然后可以在异步处理程序中解析该对象,如下所示:

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. 如果设置了myProp ,脚本将每隔0.1s检查一次。 If so, the interval is cleared and functionC is called. 如果是这样,则清除间隔并functionC

No jQuery needed in this case. 在这种情况下,不需要jQuery。

You can pass functionC as a parameter to your functionB as mention here . 您可以通过functionC作为参数传递给你的functionB如上面所提到这里

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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