Async Await / Promise / API Google JS Node Translator

Asked

Viewed 108 times

1

I started using the Google Translator API (Google Cloud Translate API) today and am unable to apply the async/await in function translate. Follows the code:

const api = require("../keys/google-translate.json").API_KEY
const googleTranslate = require("google-translate")(api);

googleTranslate.translate(text, "pt-BR", function (err, translation) {
    console.log(translation.translatedText)
});

Would have some way to make this function return a Promise so that I can use the async/await?

2 answers

4


You need to create a Promise explicitly. You have already researched the basic workings of a promise?

Basically, all Promise works like this:

const myPromise = new Promise((resolve, reject) => {
  // Quando o trabalho assíncrono estiver feito,
  // basta chamar o `resolve`, passando um valor qualquer.
  resolve(__QUALQUER_VALOR__);

  // Em um eventual erro, rejeitamos a promessa:
  reject(new Error('Whoops!'));
});

To learn more, read this excellent article by Jake Archibald and the documentation on MDN.

So in your case, just use what we saw above:

const api = require("../keys/google-translate.json").API_KEY
const googleTranslate = require("google-translate")(api);

function translateText(text) {
  // Note que a função retorna uma `Promise`. Poderemos, então, usar `async`/`await`.
  return new Promise((resolve, reject) => {
    googleTranslate.translate(text, 'pt-BR', function (err, translation) {
      if (err) {
        // No caso de erro, a promessa será rejeitada.
        reject(err);
      } else {
        // No sucesso, a promessa será resolvida.
        resolve(translation);
      }
    });
  });
}

2

In Node has the util.promisify which converts a callback function to Promise. It automatically does the process described by Luiz Felipe, but promisify attention converts only callbacks as last parameter, and callbacks that have error as first parameter.

const api = require("../keys/google-translate.json").API_KEY
const googleTranslate = require("google-translate")(api);
const util = require('util')

util.promisify(googleTranslate.translate)(text, "pt-BR");
  • 1

    Great idea. I hadn’t even thought to use the promisify... But really, it is valid!! The only problem is if the callbacks of the function are outside the standard... +1 :)

Browser other questions tagged

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