0
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).

user2066480
  • 1,229
  • 2
  • 12
  • 24
  • https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop does help, and also adds an insight on reading in sequence/paralel. Thank you. – user2066480 Jan 07 '22 at 00:29

1 Answers1

0

I got the solution from Nodejs forEach function doesn't wait for async functions: replacing the async forEach with a for loop fixes the problem. A while loop should work too. These fancy loop methods tripping people up when the simple ones do the job better!

async function updateJSON(original_JSON, assets_arr) {
  Object.keys(original_JSON).forEach(key => {original_JSON[key].active = false}); // reset all records
  for (const key in assets_arr) {
    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));
user2066480
  • 1,229
  • 2
  • 12
  • 24