[英]How to execute code after all Request are done
我有 React 應用程序,我從后端將代碼注入 DOM,在完成所有請求后我應該如何執行此代碼? 我詢問了 Vanilla 代碼,因為它是一種注入 DOM 的自定義腳本
我的意思是 API 請求,XHR 我試圖執行這個請求
document.querySelector('span[data-attribute="product_cat"]').textContent = document.querySelector('span[data-attribute="product_cat"]').textContent.replace('product cat', 'categories')
在請求期間,只有那個 product_cat div 的 Spinner instaed
我找到了一半的答案
window.addEventListener('DOMContentLoaded', (event) => { let docHeight = document.querySelector('div#page'); let MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver; let observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { if (mutation.type == 'attributes' || mutation.type == "childList" || mutation.type == "characterData" || mutation.type == 'subtree') { document.querySelector('span[data-attribute="product_cat"]').textContent = document.querySelector('span[data-attribute="product_cat"]').textContent.replace('product cat', 'categories') } }); }); observer.observe(docHeight, { attributes: true, childList: true, characterData: true, subtree: true }); });
這個在 chrome 上工作得很好,但會導致 firefox 崩潰,而且在 IE 上也不起作用
如果您希望在一組請求完成后發生某些事情,我建議使用Promise.all()
例子:
promise1 = fetch('api/some.json') // Fetch returns a `Promise`
promise2 = fetch('api/some2.json') // Fetch returns a `Promise`
Promise.all([promise1, promise2]) // [..., ...] accepts promises
.then(function (results) {
console.log("All promises are done!")
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.