google-translate-api
google-translate-api copied to clipboard
How to return result from .then() function
I try as below code, but don't work:
const Translate = require('google-translate-api');
var Tran = async (callback) => {
return await Translate('test', {from: 'en', to: 'th'});
};
console.log("Before");
console.log(Tran());
console.log("After");
Result is:
Before
Promise { <pending> }
After
Have any idea?
You need to wait until Promise is solved. If you have an array of Promise, use Promise.all(your array).then() . If you have only one value, you'll probably go for a Promise.resolve(your value).
Read mozilla doc, it has several examples: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve
Hi, I just code like below, because I need to translate line by line.
var getTran = async (text, options) => {
var _result = [];
try {
_result = await Translate(text, options);
} catch(err) {
console.log("" + err);
}
return _result;
}
var mainProcess = async (callback) => {
var result = await getTran('text', {from: 'en', to: 'th'});
// process result
result = await getTran('text2', {from: 'en', to: 'th'});
// process result
result = await getTran('text2', {from: 'en', to: 'th'});
// process result
}
mainProcess();
PS. Event I use Promise function It's not work as code below.
var result = new Promise( function(resolve , reject ) {
Translate('text', {from: 'en', to: 'th'}).then(res => {
resolve(res);
}).catch(err => {
reject(err);
});
});
console.log("Before");
console.log(result);
console.log("After");
My advice put every line in a array. Then map the array to make promise for each line. Then use promise all to get your resolved array of Promise and manipulate it.
It will look like this:
var myListOfSentence = ["sentence1", "sentence2", "sentence3"];
var i = 0;
var leng = myListOfSentence.length;
var newList = [];
while (i<leng) {
list.push(translateSentence(list[i], "en", "th")); //Return a promise
i = i+1;
}
Promise.all(newList).then( () => {
console.log(newList);
})
Use this for the translateSentence:
async function translateSentence(sentence, languebase, languagetranslation) {
var sentenceTranslated = await translate(sentence, {from: languebase, to: languagetranslation});
return sentenceTranslated;
}
Thanks
Welcome !
Good morning to you. It is still not working for me o