JavaScript - 运行 在多个 for 循环中完成所有获取请求后的回调 - 是否出错

JavaScript - Run callback after all fetch requests to finish in multiple for loops - errored or not

我正在写一些概念证明,它通过 fetch() 下载我所有的 HTML 资产。目前,我查询所有具有兼容资产的标签,并通过每个资产类型的 for 循环 运行 它。我需要做的是 运行 循环中所有请求完成后的回调函数。我试过等待,但它会一个接一个地下载每项资产。我该怎么做?

const scripts = document.querySelectorAll("script");
const links = document.querySelectorAll("link");
const images = document.querySelectorAll("img");
for (const script of scripts) {
    (async (s) => {
        const doIgnore = s.getAttribute("data-ignoreload");
        if (doIgnore) return;
        const src = s.getAttribute("data-src");
        if (!src) {
            console.error("Script does not have a data-src prop.");
            return;
        }
        fetch(src)
            .then(x => x.text())
            .then(r => {
                const newScript = document.createElement("script");
                newScript.innerHTML = r;
                document.body.appendChild(newScript);
            })
            .catch(err => {
                console.error(`Error loading script with src ${src}: ${err}`);
            });
    })(script);
}
for (const link of links) {
    (async (l) => {
        const doIgnore = l.getAttribute("data-ignoreload");
        if (doIgnore) return;
        const rel = l.getAttribute("rel");
        if (!(rel == "stylesheet")) {
            return;
        }
        const href = l.getAttribute("data-href");
        if (!href) {
            console.error("Stylesheet does not have a data-href prop.");
            return;
        }
        fetch(href)
            .then(x => x.text())
            .then(r => {
                const newStyle = document.createElement("style");
                newStyle.innerHTML = r;
                document.head.append(newStyle);
            })
            .catch(err => {
                console.error(`Error loading stylesheet with href ${href}: ${err}`);
            });
    })(link);
}
for (const image of images) {
    (async (i) => {
        const doIgnore = i.getAttribute("data-ignoreload");
        if (doIgnore) return;
        const src = i.getAttribute("data-src");
        if (!src) {
            console.error("Image does not have a data-src prop.");
            return;
        }
        fetch(src)
            .then(x => x.blob())
            .then(r => {
                const url = URL.createObjectURL(r);
                i.setAttribute("src", url);
            })
            .catch(err => {
                console.error(`Error loading image ${src}: ${err}`);
            });
    })(image);
}

将你所有的承诺推入一个数组,然后使用Promise.allSettled(promises).then((results) => {})

文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled

示例:

const promises = images.map(async (image) => {
    // do some async work
    return fetch(whatever); // don't .catch this

})

Promise.allSettled(promises).then((results) => {
  // results is a result of errors or successes
})