How to return a value instead of a [Object Promise]

Asked

Viewed 303 times

1

I have this code and want to return the string not to Promise, but I do not know how exactly to do, I tried to look at other solutions on the site but I could not apply them in my code. (I’m using the Aces)

async function traduzCategoria(texto)
{
    if (typeof texto === "undefined"){
        return "sem categoria";
    }

    let textoUrl = texto[0].replace(/ /gi, "+");
    textoUrl = texto[0].replace(/&/gi, "and");

    let urlYandex = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + keyYandex 
        + "&text=" + textoUrl + "&lang=pt";

    let res = await axios.get(urlYandex)
                .then(function (response) {

                    let textoTraduzido = response.data.text[0];
                    return textoTraduzido;

                })
                .catch(function (erro) {
                    return "erro na categoria";
                })


    return res;
}

The function does not wait for the file to return the value.

1 answer

1

You are using async/await syntax incorrectly. The correct would be:

try {
    const response = await axios.get(urlYandex);

    return response.data.text[0];
} catch(error) {
    return error;
}

If using the then/catch of Promise returned by Xios, remove the syntax of async/await, which was made exactly to make the code less verbose.

I’m available, see you later.

  • 1

    I wouldn’t say using the await how he did is "wrong"... After all, the then is returning another Promise.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.