简体   繁体   中英

Json object model is not updated

I want to update the json object model values like the code below. But it does not seems to update the model when I change the values.

I have tried removing the async code, that seems to work. why async code does not to work? Can some one please explain me. Thanks

var json = {
  lang: "es",
  country : "Spain", 
  city : {
    cityname : "name"
  }  
};

async function asynctranslateText() {
  return new Promise((resolve, reject) => {
    resolve("OK");
  });
}

async function modifyJson(en) {
  Object.keys(en).forEach(async function (item) {
    if (typeof en[item] === 'object') {
      await modifyJson(en[item]);
    } else {
      en[item] = await asynctranslateText();
    }    
  });
}

 (async () => {
  await modifyJson(json);
  console.log(json);
 })();

Output
{ lang: 'es', country: 'Spain', city: { cityname: 'name' } }

Expected output:
{ lang: 'OK', country: 'OK', city: { cityname: 'OK' } }

modifyJson should return a promise in order to be await ed.

Since functions marked async implicitly return promises, you can use Array.map as opposed to forEach with an async function to generate an array of promises.

Then simply use Promise.all to wait for all of them to complete.

Note that modifyJson and asyncTransalateText itself here doesn't need to be marked as async . Typically a function should not be marked as async AND return a promise.

 var json = { lang: "es", country: "Spain", city: { cityname: "name" } }; function asynctranslateText() { return new Promise((resolve, reject) => { resolve("OK"); }); } function modifyJson(en) { return Promise.all(Object.keys(en).map(async function(item) { if (typeof en[item] === 'object') { await modifyJson(en[item]); } else { en[item] = await asynctranslateText(); } })); } (async() => { await modifyJson(json); console.log(json); })();

If you use a for.. of loop to enumerate the object keys, the result will be as expected.

The original issue is that modifyJson will not have executed when we log the output.

 var json = { lang: "es", country: "Spain", city: { cityname: "name" } }; async function asynctranslateText() { return new Promise((resolve, reject) => { resolve("OK"); }); } async function modifyJson(en) { for(let item of Object.keys(en)) { if (typeof en[item] === 'object') { await modifyJson(en[item]); } else { en[item] = await asynctranslateText(); } } } (async () => { await modifyJson(json); console.log(json); })();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM