我正在进行一个SPA(单页应用程序(项目,需要以动态和可控的方式(CSS、HTML和JS(加载文件
我创建了下面的结构(在本例中仅用于CSS(,但尽管文件被注入到页面中,但承诺从未被解决
该结构的一个特点是;"解决";以及";拒绝";每个";承诺;所创建的被保存以在原始"程序"之外执行;承诺;功能
这是必要的,因为如果";承诺;如果成功,必须删除控制事件,如果发生错误,则必须删除元素
'use strict';
const
css=
(
()=>
{
const
load=
url=>
{
return new Promise(
(resolve,reject)=>
{
let
link=document.createElement("link");
link.setAttribute("href",url);
link.setAttribute("rel","stylesheet");
link.addEventListener("load",onSuccess);
link.addEventListener("error",onError);
resolveAhead=resolve;
rejectAhead=reject;
document.head.appendChild(link);
}
);
},
onSuccess=
event=>
{
event.target.removeEventListener("load",onSuccess);
event.target.removeEventListener("error",onError);
resolveAhead(event);
},
onError=
event=>
{
document.head.removeChild(event.target);
rejectAhead(event);
};
let
resolveAhead,
rejectAhead;
return {
load
}
}
)();
Promise.all(
[
css.load("style1.css"),
css.load("style2.css"),
css.load("style3.css"),
css.load("style4.css"),
css.load("style5.css"),
css.load("style6.css")
]
).then(
response=>
{
console.log(response);
alert("Well done");
}
).catch(
response=>
{
console.log(response);
alert("Houston... we've had a problem here");
}
);
您的问题是有两个变量:
let resolveAhead, rejectAhead;
第一次调用.load()
时,将它们设置为正在构建的新Promise的解析和拒绝函数。但是,下次调用.load()
时,您将再次创建一个新的Promise,并覆盖这些变量以作为新Promise的解析/拒绝。然后只能调用最后构造的Promise中的resoly/reject函数。
您可以在load()
函数中创建对这些函数的引用,这样对load()
的进一步调用就不会影响已经定义的resolveAhead和rejectHead函数:
'use strict';
const css = (() => {
const load = url => {
let resolveAhead, rejectAhead;
const onSuccess = event => {
event.target.removeEventListener("load", onSuccess);
event.target.removeEventListener("error", onError);
resolveAhead(event);
};
const onError = event => {
document.head.removeChild(event.target);
rejectAhead(event);
};
return new Promise(
(resolve, reject) => {
let link = document.createElement("link");
link.setAttribute("href", url);
link.setAttribute("rel", "stylesheet");
link.addEventListener("load", onSuccess);
link.addEventListener("error", onError);
resolveAhead = resolve;
rejectAhead = reject;
document.head.appendChild(link);
}
);
};
return {load};
})();
Promise.all([
css.load("https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"),
css.load("https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css"),
]).then(response => {
console.log(response);
alert("Well done");
}).catch(response=> {
console.log(response);
alert("Houston... we've had a problem here");
});