簡體   English   中英

在執行另一個函數之前等待一個函數完成

[英]Waiting for one function to finish before another is executed

我使用此代碼基本上切換到數據表中的下一行,但是,在切換到並使用數據表中的下一行之前,我已經對我的應用程序進行了編程,以通過提示用戶檢查更改和/或保存它們。

但是,我不喜歡這種編碼的一點是,在單擊“確定”按鈕保存更改之前,另一半代碼會觸發。 如何使用 onclick 函數等待 RealTimeSave() 函數完成將更改寫回數據庫,然后將視圖切換到數據表中的下一行?

var table = document.getElementById("data");
var tbody = table.getElementsByTagName("tbody")[0];

tbody.onclick = function(e) {

    if (document.getElementById('data')) {

        if(!document.getElementById('save').disabled) { 

            if (confirm("IMTS has detected unsaved changes, would you like to save the changes now?") == true) {
                RealTimeSave()
            }
        }

    }

    e = e || window.event;
    var td = e.target || e.srcElement
    var row = (td.tagName == "DIV") ? td.parentNode.parentNode : td.parentNode;

    if (ishigh&&ishigh!=row) {
        ishigh.className = ''
    }
    row.className = row.className==="highlighted" ? "" : "highlighted";
    ishigh=row;

    getdata(row)
}

看看 promise 和 deferred 對象,因為它們可以解決推遲執行的問題: javascript promises

您的問題缺乏足夠的信息,但根據您對問題的描述,我假設RealTimeSave()執行一些異步任務。 您能做的最好的事情是更改負責更新數據庫的回調(IndexedDB?),但另一種解決方案是將您的更新后邏輯包裝在函數表達式中,並將其作為參數傳遞給setTimeout()與另一個參數(延遲)為0 下面是一個例子:

// slightly reorganized the code, feel free to stick with your style

var highlighted;
document.querySelector('#data > tbody').addEventListener('click', function (e) {
  if (!document.querySelector('#save').disabled &&
      confirm('IMTS has detected unsaved changes, ' +
              'would you like to save the changes now?')) {
    realTimeSave(); // this triggers an asynchronous task...
  }

  // ...and so does this, but the task is queued
  setTimeout(function () {
    var target = e.target;
    var row = target.parentNode;
    if (target.tagName === 'DIV') {
      row = row.parentNode;
    }
    if (highlighted && highlighted !== row) {
      highlighted.classList.remove('highlighted');
    }
    row.classList.toggle('highlighted');
    highlighted = row;
    getData(row);
  }, 0);
});

由於事件循環在 JavaScript 中的工作方式,作為setTimeout()的第一個參數傳遞的函數將等到之前添加的所有消息(事件和其他)都被處理。 請注意,傳遞 0 作為延遲並不能保證該函數會立即執行,但您可以確定執行將在之前添加的所有異步任務完成后發生。 因此,假設您使用的是 IndexedDB 並且您的代碼樣板如下所示:

dbTransaction.oncomplete = function (e) {
  // ...
};
// or
dbRequest.onsuccess = function (e) {
  // ...
};

...使用setTimeout()就足夠了。 但是,如果您通過 AJAX 連接到在線數據庫接口,那么您唯一的選擇(假設承諾 - 在另一個答案中提到 - 不可用)是掛鈎 AJAX 成功回調並相應地更新您的接口邏輯。

暫無
暫無

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

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