async function updateJSON(original_JSON, assets_arr) {
Object.keys(original_JSON).forEach(key => {original_JSON[key].active = false}); // reset all records
Object.keys(assets_arr).forEach(async key => {
let idx = original_JSON.findIndex(x => x.name === assets_arr[key].name);
if (idx === -1) { // no match -> insert a new record
const code_nr = await getCode(assets_arr[key].token_id);
let debug = original_JSON.push({ name: assets_arr[key].name, active: true, code: code_nr });
console.log("List len now:", debug);
} else { original_JSON[idx].active = true; } // there is a match, so just update existing record to become 'active'
});
return original_JSON;
}
console.table(await updateJSON(original_JSON, assets_arr));
I cannot figure out a way for the code to wait for await getcode to finish before returning the function. I get a partial execution immediately and only then the code related to original_JSON.push is executed one record at the time.
If I remove async from line 3 and await from line 6 the function is executed sequentially(synchronously?), except then I get "Promise { }" instead of the code number the getCode function is supposed to retrieve. This number comes from a URL fetch().
I did read Async/Await not waiting and I think my problem is related. Do I need to use map() instead of forEach()? I find map() confusing. I do want to mutate the array, I'm not interested in making a new one (although I'll do it if that's what will fix this).