I'm trying to translate all elements of the array wordList
and pushing them to a new list translatedWordList,
but because translate()
is async the new list is empty when I callback or return it
function translateWordList(wordList, callback) {
var translatedWordList = [];
wordList.forEach((word) => {
translate(word, (translation) => {
translatedWordList.push(translation);
});
});
callback(translatedWordList);
}
I tried to solve this by delaying the callback using a while loop that runs until the length of translatedWordList
and wordList
match, but the function translate is not logging anything
function translateWordList(wordList, callback) {
var translatedWordList = [];
wordList.forEach((word) => {
translate(word, (translation) => {
translatedWordList.push(translation);
console.log(translation)
counter++;
});
});
while (translateWordList.length < wordList.length) {}
callback(translatedWordList);
}