Friday, 5 May 2017

How to handle loop and promise?

I am making a small script to quickly and easily translate json recursively. I use Promised.

I tried to do a loop but the iterator is (of course) changing with the loop.

var request = require('request');
var translateFile = require("./translate");
const merge = require("./objectmerge");
var fs = require("fs");
var path = require('path')

var language = ["en", "es"]


var OPTION = {
    url: 'http://www.transltr.org/api/translate?text=monde&to=en',
    method: "POST",   
}

let createForm = (text, originLanguage, targetLanguage) => {
    return {
        "text": text,
        "from": originLanguage,
        "to": targetLanguage
    }
}
let translateIt = (text, originLanguage, targetLanguage) => {
    option = merge.mergeDeep({}, OPTION);
    option.form = createForm(text, originLanguage, targetLanguage);
    return new Promise((resolve, reject) => {
        request(option, function(error, response, body) {
            resolve(body);
            // console.log('error:', error); // Print the error if one occurred 
            // console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received 
            // console.log('body:', body); // Print the HTML for the Google homepage.
        });
    })
}


let iterateOnJson = (jsonObj, originLanguage, TargetLanguage) => {
    var promiseAll = [];
    let jsonObjClone = merge.mergeDeep({}, jsonObj);
    let iterateInner = (jsonObj) => {
        for (let item in jsonObj) {
            if (typeof(jsonObj[item]) == "string") {
                let promise = translateIt(jsonObj[item], originLanguage, TargetLanguage).then(translatedWord => jsonObj[item] = JSON.parse(translatedWord).translationText);
                promiseAll.push(promise);
            } else {
                iterateInner(jsonObj[item])
            }
        }

    }
    iterateInner(jsonObjClone);
    return Promise.all(promiseAll).then(data => {
            return jsonObjClone;
        })
    }


//HERE IS THE LOOP
    for (var lang of language) {
        console.log(lang);
        iterateOnJson(translateFile, "fr", lang).then(value => {
            let fileTitle = lang;
            fs.writeFile("mypath/" + fileTitle + i + ".json", JSON.stringify(value),
                function(err) {
                    if (err) {
                        return console.log(err);
                    }
                    console.log("The file was saved!", lang);
                });
        });
    }

Loop is working correctly, it goes through the array. But both file is saved as "es.json" because the lang value is changing with loop. I thought it would pass the value not the reference. Should I change the way I am approching it ?

Also, I don't know how to phrase the title of my problem.



via Stefdelec

No comments:

Post a Comment