Last active
September 12, 2018 01:11
-
-
Save tanayv/4da9665c68dbe6aafcad82321a3c3d89 to your computer and use it in GitHub Desktop.
Flattening Promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const translateSongLyrics = (songLines, callback) => { | |
let config = { | |
headers: { | |
'Content-Type': 'application/x-www-form-urlencoded' | |
} | |
}; | |
let endpoint = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + yandexApiKey; | |
songLines.forEach((line) => { | |
let requestBody = { | |
text: removeHTMLTags(line), | |
lang: 'fr-en' | |
let request = axios.post(endpoint, querystring.stringify(requestBody), config); | |
/* Storing each promise returned from the requests into a promise chain */ | |
promiseChain.push(request); | |
}) | |
let combinedChain = []; | |
/* Evaluating all the promises together with a single .then() */ | |
Promise.all(promiseChain) | |
.then((response) => { | |
let translationIndex = 0; | |
songLines.forEach((songLine) => { | |
combinedChain.push({ | |
original: removeHTMLTags(songLine), | |
translation: response[translationIndex].data.text[0] | |
}); | |
}) | |
callback(combinedChain); | |
}, | |
(error) => { | |
console.log("There was an error in translation", error); | |
callback([]); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment