From 79db9af564527b319b8167f360fd4d42edb06160 Mon Sep 17 00:00:00 2001 From: Nithin <141642443+nithintejesh@users.noreply.github.com> Date: Tue, 9 Jul 2024 20:28:24 +0530 Subject: [PATCH] Update batchTrans.js --- examples/googleTranslate/batchTrans.js | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/examples/googleTranslate/batchTrans.js b/examples/googleTranslate/batchTrans.js index 62bc5d3..e53aa14 100644 --- a/examples/googleTranslate/batchTrans.js +++ b/examples/googleTranslate/batchTrans.js @@ -2,11 +2,23 @@ const { GoogleTranslator } = require("../../src/dolmetscher"); const google = new GoogleTranslator("en", "auto"); +async function translateTextSafely(google, text) { + try { + const translation = await google.translateText(text); + return { success: true, translation }; + } catch (error) { + return { success: false, error: error.message }; + } +} + function batchTranslation() { - const texts = ["bonsoir le monde", "Hallo Welt", "guten morgen"]; - google - .translateBatch(texts) - .then(res => console.log("batch translation: ", res)); + const texts = ["bonsoir le monde", "Hallo Welt", "guten morgen", ""]; // Added an empty string to test error handling + + const translationPromises = texts.map(text => translateTextSafely(google, text)); + + Promise.all(translationPromises) + .then(res => console.log("batch translation: ", res)) + .catch(err => console.error("Error in batch translation: ", err)); } batchTranslation();