I am trying to create a translation app that uses google translation API.
Code
const apiTranslate = (() => {
const _API_KEY = "api-key";
async function getTranslation(text) {
let res = await axios.post(
`https://translation.googleapis.com/language/translate/v2?key=${_API_KEY}`,
{ q: text, target: "de" }
);
let translation = res.data.data.translations[0].translatedText;
console.log(translation);
return translation;
}
return Object.assign({}, {getTranslation});
})();
let text = "hello world";
const {getTranslation} = apiTranslate;
const message = getTranslation(text);
console.log(message);
It returns: A promise object with prototype, promiseState and promiseResult properties.
It should return: Hello walt.
The value of translation is correct as I log it in the code.
2
Answers
Yeah. you are right.
getTranslation
will return a promise as its anasync
function.So, you can use either an await or then to get the return from it.
One:
In your case, if you want to read the data in your script body,
Two:
Or if you want to assign to a variable
message
for further processing, then, you need to write a function.Three:
Another approach declares an immediate calling function.