簡體   English   中英

強制代碼在另一個方法完成執行后執行

[英]Force code to execute after another method finishes executing

這是我想要做的:

setSource是一個執行約3秒的函數。

 editor.setSource();

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

我想//執行某些操作,在執行setSource()的最后一行之后執行一些命令。 現在我正在使用setTimeout,但我認為這不是一個很好的解決方案,因為有時setSource()可能需要5秒才能執行。 這個怎么做?

setSource接受一個回調參數:

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

然后傳遞下一個代碼塊作為回調執行:

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

如果您可以訪問jQuery的延遲對象,可以在這里使用它們:

  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!");
});

如果您正在使用AJAX或動畫或其他已經使用延遲對象的jQuery任務,您只需返回其結果值而不是創建自己的延遲對象:

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

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

確保查找如何解決拒絕延遲對象以及如何處理這些對象。

這個答案使用了promises ,這是ECMAScript 6標准的JavaScript特性。 如果您的目標平台不支持promises ,請使用PromiseJs填充它。

在較新的瀏覽器版本中,您可以使用ES6 promises editor.setSource()將其執行包裝到Promise並返回它,因此可以繼續使用其他函數。

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

要繼續使用其他函數,只需在promise上使用then方法即可。

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

我也在尋找解決方案,我想在上一個函數完全執行后才執行我的第二個函數,我嘗試了回調函數但仍然沒有得到解決方案,最后我發現使用簡單的$.ajax({ });解決這個問題的最簡單方法$.ajax({ }); 方法代碼對我有用:)。

例如,

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

就是這樣,在這個代碼中,url參數將調用第一個函數,並且只有在其執行函數2成功時才會調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM