简体   繁体   中英

How to execute code after all Request are done

I have React app, and I inject code into DOM from backend, How should I execute this code after All Request are done? I asking about Vanilla code because it's kind of custom script injected into the DOM

I Mean API request, XHR I trying to execute this one

document.querySelector('span[data-attribute="product_cat"]').textContent = document.querySelector('span[data-attribute="product_cat"]').textContent.replace('product cat', 'categories')

During request there is only spinner instaed of that product_cat div

I found half-answer

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

This one work pretty well on chrome, but causes firefox crash, and also not working on IE

If you want something to happen after a set of requests are finished, I would recommend using Promise.all()

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM