我正在try 解析一个JSON对象,它有一个type
键,其值是一个字符串;如果类型是"a",则对象类定义在"a.js"中,并且此文件包含一个初始化函数a_init
.可能有一个subobjects
键,其值是一个对象array.如果是这样,这些嵌套对象应该以相同的方式处理.
我拥有的代码如下所示:
var files = [];
function load(obj) {
if (!!obj["type"]) {
let type = obj.type;
let subobjects = obj.subobjects;
let promise = new Promise(function(resolve) {
let script = document.createElement("script");
script.setAttribute("src", type + ".js");
script.addEventListener("load",resolve);
document.head.appendChild(script);
});
promise.then(function() {
if (!files.includes(type)) {
files.push(type);
if (subobjects instanceof Array) {
for (element of subobjects) {
load(element);
}
}
let func = window[type + "_init"];
if (typeof(func) =="function") {
func(obj);
}
}
});
}
}
对于这样的对象:
{ "type": "a",
"data": "foo",
"subobjects": [
{ "type": "b",
"data": "1"
}
]
}
输出为:
This is A
This is B
(函数a_init
和b_init
仅显示用于测试目的的消息.)
我的问题是,我希望在外部对象之前初始化子对象,因此b_init
将在a_init
之前完成,以提供以下输出:
This is B
This is A
但是当然,对load
的嵌套调用只是创建一个新的promise,然后在新的promise之前完成.
这里有没有办法强制同步性来控制事件的顺序?