Skip to content

Instantly share code, notes, and snippets.

@tanayv
Last active September 12, 2018 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanayv/4da9665c68dbe6aafcad82321a3c3d89 to your computer and use it in GitHub Desktop.
Save tanayv/4da9665c68dbe6aafcad82321a3c3d89 to your computer and use it in GitHub Desktop.
Flattening Promises
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