javascript 在另一个方法完成执行后强制执行代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15360393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:31:20  来源:igfitidea点击:

Force code to execute after another method finishes executing

javascript

提问by petko_stankoski

Here is what I want to do:

这是我想要做的:

setSource is a function which executes about 3 seconds.

setSource 是一个执行大约 3 秒的函数。

 editor.setSource();

 setTimeout(function () {
      //do something, some commands
 }, 3000);

I want the //do something, some commands part to be executed AFTER the last line of setSource() is executed. Now I'm doing it with setTimeout, but I think it's not very good solution, because sometimes setSource() will take maybe 5 seconds to execute. How to do this?

我希望 //do something, some commands 部分在 setSource() 的最后一行执行后执行。现在我用 setTimeout 来做,但我认为这不是很好的解决方案,因为有时 setSource() 可能需要 5 秒才能执行。这个怎么做?

回答by Waleed Khan

Have setSourcetake a callback argument:

setSource一个回调参数:

editor.setSource = function(callback) {
    // do editor things
    callback();
}

Then pass the next block of code to be executed as a callback:

然后传递下一个要作为回调执行的代码块:

editor.setSource(function() {
    // do some other things
});


If you have access to jQuery's deferred objects, you can make use of them here:

如果您可以访问 jQuery 的延迟对象,则可以在此处使用它们:

  1. Make a new deferred object.
  2. Start the timeout to do your long task.
  3. Return the deferred object.
  4. In the timeout, once the task is complete, call deferred.resolve.
  1. 创建一个新的延迟对象。
  2. 开始超时以完成您的长期任务。
  3. 返回延迟对象。
  4. 在超时时间内,一旦任务完成,调用deferred.resolve.

 

 

editor = {
    setSource: function() {
        var deferred = $.Deferred();

        console.log("Beginning editor.setSource...");

        setTimeout(function() {
            // This function took a while to occur
            deferred.resolve();
        }, 3000);

        return deferred;
    }
}

$.when(editor.setSource()).then(function() {
    console.log("Editor is done!");
});

If you're doing AJAX or animation or another jQuery task that uses deferred objects already, you can just return its result value instead of making your own deferred object:

如果您正在执行 AJAX 或动画或其他使用延迟对象的 jQuery 任务,您可以只返回其结果值,而不是创建自己的延迟对象:

editor = {
    setSource: function() {
        return $.get({
            url: "myurl.com/mypage",
            data: $("#myform").serialize()
        });
    }
}

$.when(editor.setSource()).then(function() {
    console.log("Editor is done!");
});

Make sure to look up how you can either resolveor rejectdeferred objects, and how to handle those.

请务必查看如何解决拒绝延迟对象,以及如何处理这些对象。

回答by Domysee

This answer uses promises, a JavaScript feature of the ECMAScript 6standard. If your target platform does not support promises, polyfill it with PromiseJs.

这个答案使用标准promises的 JavaScript 特性ECMAScript 6。如果您的目标平台不支持promises,请使用PromiseJs对其进行polyfill

In newer browser versions you can use ES6 promises. editor.setSource()wraps its execution into a Promiseand returns it, so it can be continued with other functions.

在较新的浏览器版本中,您可以使用ES6 promises. editor.setSource()将其执行包装到 a 中Promise并返回它,因此它可以继续执行其他函数。

editor.setSource = function(){
    return new Promise(function(fulfill, reject){
        //do your work
        fulfill(resultValue);
    });
};

To continue it with another function simply use the thenmethod on the promise.

要继续使用另一个函数,只需使用thenPromise 上的方法。

var promise = editor.setSource();
promise.then(function(result){
    //do something more
});

回答by Gopinath Khandalkar

I was also looking for solution where I want to execute my second function only after previous function gets executed completely, I tried callback function but still not getting the solution, finally I find the very easiest way to resolve this issue by using simple $.ajax({ });method code which works for me :).

我也在寻找解决方案,我想在前一个函数完全执行后才执行我的第二个函数,我尝试了回调函数,但仍然没有得到解决方案,最后我找到了解决这个问题的最简单$.ajax({ });方法,使用简单的方法代码对我有用:)。

for example,

例如,

$.ajax({
  url: function1(),
  success: function(){
    //function 2 code here or just call function2() here
  }
}); 

that's all, in this code url parameter will call first function and only on the success of its execution function 2 will be called.

就是这样,在这段代码中 url 参数将调用第一个函数,并且只有在其执行成功时才会调用函数 2。