I am trying to deserialise a JSON object which has a type key whose value is a string; if the type is "a", the object class is defined in "a.js" and this file contains an initialisation function a_init. There may be a subobjects key whose value is an array of objects. If so, these nested objects should be processed in the same way.
The code I have looks like this:
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);
}
}
});
}
}
For an object like this:
{ "type": "a",
"data": "foo",
"subobjects": [
{ "type": "b",
"data": "1"
}
]
}
the output is:
This is A
This is B
(The functions a_init and b_init just display a message for testing purposes.)
My problem is that I would like the subobjects to be initialized before the outer object, so b_init would complete before a_init to give this output:
This is B
This is A
but of course the nested call to load just creates a new promise and then completes before the new promise does.
Is there any way to enforce synchronicity here to control the order of events?
You should convert your
loadfunction toasyncand inside itawaitfor the promise and also for the recursive calls to finish.