skip to Main Content

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


  1. async function translateText() {
        let text = "hello world";
        const {getTranslation} = apiTranslate;
        try {
             getTranslation(text).then((res=>{
                console.log(res)
             }));
           
        } catch (error) {
            console.error("Error during translation:", error);
        }
    }
    
    Login or Signup to reply.
  2. Yeah. you are right. getTranslation will return a promise as its an async 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,

    let text = "hello world";
    const {getTranslation} = apiTranslate;
    
    getTranslation(text).then(message=>{
        console.log(message);
    });
    

    Two:
    Or if you want to assign to a variable message for further processing, then, you need to write a function.

    const doTranslate = async ()=> {
        let text = "hello world";
        const {getTranslation} = apiTranslate;
        const message = await getTranslation(text);
        console.log(message);
    }
    

    Three:
    Another approach declares an immediate calling function.

    (async () => {
        let text = "hello world";
        const { getTranslation } = apiTranslate;
        const message = await getTranslation(text);
        console.log(message);
    })();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search