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);
}
});
});
}
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 :)– Luiz Felipe