google-translate-api icon indicating copy to clipboard operation
google-translate-api copied to clipboard

How to return result from .then() function

Open yoyhosoft opened this issue 7 years ago • 7 comments

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?

yoyhosoft avatar Oct 18 '17 07:10 yoyhosoft

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

popo63301 avatar Oct 24 '17 08:10 popo63301

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");

yoyhosoft avatar Oct 24 '17 09:10 yoyhosoft

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);
})

popo63301 avatar Oct 24 '17 09:10 popo63301

Use this for the translateSentence:

async function translateSentence(sentence, languebase, languagetranslation) {

var sentenceTranslated = await translate(sentence, {from: languebase, to: languagetranslation});

return sentenceTranslated;

}

popo63301 avatar Oct 24 '17 09:10 popo63301

Thanks

yoyhosoft avatar Oct 24 '17 10:10 yoyhosoft

Welcome !

popo63301 avatar Oct 24 '17 10:10 popo63301

Good morning to you. It is still not working for me o

Tahywoh avatar Jul 16 '18 00:07 Tahywoh