Javascript Promises: Iterate over all object keys arrays and then resolve

Gus picture Gus · Nov 22, 2016 · Viewed 12.6k times · Source

I have this JS object:

let setOfWords = {
    "nouns": [
        "work",
        "construction",
        "industry"
    ],
    "verbs": [
        "work"
    ],
}

I'm using the google translate API which calls a REST resource, so I need to wait for the response of each translation and then resolve the same object structure but with the translated words.

function translateByCategory(){
    let translatedObj = {};
    return new Promise(function(resolve, reject){

        Object.keys(obj).forEach(function(category){
            if (translatedObj[category] == undefined) {
                translatedObj[category] = [];
            }
            setOfWords.forEach(function(word){
                google.translate(word, 'es', 'en').then(function(translation){
                    translatedObj[category].push(translation.translatedText);
                });
            });

            // return the translatedObj until all of the categories are translated
            resolve(translatedObj);
        });
    });
}

Answer

hackerrdave picture hackerrdave · Nov 22, 2016

You can use Promise.all() to wait for all promise fulfillments (or first rejection)

var translateRequests = [];

Object.keys(setOfWords).forEach(function(category){
        setOfWords[category].forEach(function(word){
            translateRequests.push(google.translate(word, 'es', 'en'));
        });
    });
});

Promise.all(translateRequests).then(function(translateResults){
    //do something with all the results
});

See docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all