I have a Javascript function that looks like this in a personal project:
function buildSettings(settings_file_names){
return new Promise(function(resolve, reject){
let settings = {};
settings.files = {};
settings.getFile = function(file_name){
return this.files[file_name];
}
settings_file_names.forEach((file_name) => {
settings.files[file_name] = getLocalFile(file_name);
//getLocalFile() returns a promise.
});
Promise.all(Object.values(settings.files)).then(() => {
for (let filename in settings.files){
if (filename.includes(".json")){
settings.files[filename].then((filedata) => {
if (filedata){
console.log("Parsing into JSON!");
settings.file[filename] = JSON.parse(filedata);
}else{
settings.file[filename] = null;
}
});
}
}
console.log("About to resolve!");
resolve(settings);
});
});
}
And the console output looks like this:
utility_functions.js:148 About to resolve!
utility_functions.js:135 Parsing into JSON! (x8)
However, I need to wait to extract the values of those promises and parse them into JSON before resolving the overarching promise. I need to wait for what happens in the then()s. Is there a way to do this? Or am I facing this issue because I'm doing something wrong in a broader sense?
I expected then() to give me the value of a Promise synchronously if I already waited for that Promise to be fulfilled (as I think I did with Promise.all()). In reality then() seems to behave asynchronously even if the Promise is fulfilled.
Thank you in advance for any insight!