Escribí el siguiente código para traducir del árabe al inglés, quiero que la función acepte el inglés como fuente y devuelva el texto traducido,
¿Alguien me puede ayudar en esto?
translateArtoEn(source) { let url = `https://translation.googleapis.com/language/translate/v2?key=${API_KEY}`; url += '&q=' + encodeURI(source); url += `&source=ar`; url += `&target=en`; console.log(url) fetch(url, { method: 'GET', headers: { "Content-Type": "application/json", Accept: "application/json" } }) .then(res => res.json()) .then((response) => { return response.data.translations[0]["translatedText"] }) .catch(error => { console.log("There was an error with the translation request: ", error); }); }El código que proporcionó no devolverá ningún valor ya que asumo que la función es síncrona.
Con esto, puede usar la función de callback de llamada para devolver el resultado deseado después de que la función principal ya haya regresado.
Consulte el siguiente código para su referencia:
const fetch = require('node-fetch'); function main(){ var source = '<your_desired_text_to_translate>'; translateArtoEn(source,myDisplayer); } function translateArtoEn(source,callback){ var API_KEY = '<your_API_key>'; let url = `https://translation.googleapis.com/language/translate/v2?key=${API_KEY}`; url += '&q=' + encodeURI(source); url += `&source=ar`; url += `&target=en`; fetch(url, { method: 'GET', headers: { "Content-Type": "application/json", Accept: "application/json" } }) .then(res => res.json()) .then((response) => { callback(response.data.translations[0].translatedText) }) .catch(error => { console.log("There was an error with the translation request: ", error); }); } function myDisplayer(result) { // handle the result here console.log("Translated text: ",result); } if (require.main === module) { main(); } En este código, la callback de llamada se usa para pasar el valor devuelto (después de que finaliza la ejecución de la función principal) a otra función que manejará el resultado.