簡體   English   中英

當函數包含異步操作時,如何按順序對同一函數進行多次調用

[英]How to make multiple calls to the same function fire in order, when function includes asynchronous actions

我正在處理競爭條件,並試圖弄清楚如何解決它。

我有多段代碼調用相同的函數。 此函數調用 API 端點上的fetch並根據結果進行 DOM 修改。 該函數可以在頁面加載時調用,或者響應用戶操作。 用戶可以多次觸發函數調用。

如果稍后調用的 DOM 修改發生在先前調用的修改之前,事情就會被破壞,這種情況偶爾會發生。

是否有一種通用模式可以確保這些 DOM 修改按順序發生,即使 fetch 調用沒有?

我正在考慮創建某種隊列,在調用該方法時將帶時間戳的行添加到數組中,然后在獲取完成時將fetch結果附加到該行,然后在時間戳列表中進行所有 DOM 修改直到我連續打了沒有結果。 這是否有意義,或者是否有現成的解決方案或我在這里缺少的常見模式?

function getContent() {
    fetch(url)
        .then((response)) => modifyDOM(); // Make this part run in sequence.
}

// for reasons not shown here, the first call takes so long that the second one
// completes its DOM modification first. This race condition breaks my content.
getContent();
getContent(); 

您可以跟蹤在調用函數時重新分配給新請求的持久性 Promise:

let prom = Promise.resolve();
function getContent() {
    const promToReturn = prom
      .then(() => fetch(url))
      .then(modifyDOM);
    // continue the chain even if there's an error during one of them
    prom = promToReturn.catch(() => undefined);
    // while returning the original Promise whose results and errors can be seen outside
    return promToReturn;
}

這樣,最多只能在任何時間進行一個請求。 getContent順序調用一次只會產生一個正在進行的請求。 getContent(); getContent(); 將導致一個請求,它完成並修改 DOM,然后在完成之后,另一個請求然后修改 DOM。

暫無
暫無

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

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