How to get a re-formatted json object after looping over it and making asynchronous promise calls

Viewed 107

Not sure if the question is right or wrong. Let me just describe the problem for a better understanding. Consider a multi-level json object with keys having random english text strings as their values. The task is to iterate over the object and visit every node to create another equivalent object containing translated texts for those english strings having same keys (and level) with same parent object as before. Using recursions the translation is working, however from within a promise it is never returning the final translated object. There are no errors though.

Object:

var obj =   {
  "MENU": {
    "NODE": "Wait for her",
    "RESPONSE": {
      "ATTR": "We'll meet again",
      "SEMANTICS": "The Dark Knighthood"
    }
  },
  "NODES": {
    "STANDARDLIBRARY": {
      "SERVER": "Never say never again",
      "CATEGORIES":{
        "INFOPROTECTION":"Infoprotection",
        "DATAMOTION":"Data In Motion",
        "LOGGING":"Loggin is key to debugging",
        "VERACITY": "Help me understand the best I can",
        "VARIETY": "Silver surfer"
      }
    }
  }
};

Code:

const iterateAttributesAndParseJSON = (o) => {
  return new Promise(
   function (resolve, reject) {
      for(var a in o) {
        if (typeof o[a] == 'object'){
          iterateAttributesAndParseJSON(o[a])
        }else{
          if( o[a] != '' ) {
            translate(o[a], {from: 'en', to: 'nl'}).then( res => {
                //return jsonObj[a]=res.text;
                jsonObj[a]=res.text;
                //console.log(jsonObj);
                resolve(jsonObj);
            }).catch(err => {
              console.error(err)
                reject(err);
            });
          }
        }
      }
     }
   );
}

iterateAttributesAndParseJSON(obj).then(asd => { console.log(`Resolved:`,  asd) }, err => console.log(err))

Note: Translate is again thenable. I used this npm module. google-translate-api

2 Answers
Related