0

I would like to make a little translator function which uses the Bing Translator. I could do that and works perfectly, but when i try to call it from my code, and expecting the output I got nothing. I figured out why, because the actual code does not waiting for the translator to return the text. I tried using async await but I could not get working. Please help me.

The code where I would like to call the translator in every foreach element.

        let msg = {};
        error.details.forEach( e => {
           const translated = translate("hello world");
           console.log(translated)
           msg[e.path] = translated;
        });
        return res.status(400).send(msg)

Thsi is the translate.js file:

const request = require('request');
const uuid = require('uuid');

async function translate(string) {
    var key_var = process.env.T_KEY;
    var endpoint_var = process.env.T_END;

    let options = {
        method: 'POST',
        baseUrl: endpoint_var,
        url: 'translate',
        qs: {
        'api-version': '3.0',
        'to': ['hu']
        },
        headers: {
        'Ocp-Apim-Subscription-Key': key_var,
        'Content-type': 'application/json',
        'X-ClientTraceId': uuid.v4()
        },
        body: [{
            'text': 'hello world'
        }],
        json: true
    };

    request(options, async function(err, res, body){
        const response = await body[0].translations[0].text;
        return response;
    });
}

module.exports.translate = translate;

Please dont judge me, I am learning this whole new thing by writing code, but here i am stuck. I read many articles about promises but I could not understand properly. I hope somebody could help me a little bit. Thanks in advance.

  • Hey, I was just in a thread that might help you where people talked about forEach and async function execution and how to handle them https://stackoverflow.com/questions/61436985/javascript-simple-async-issue/61437030?noredirect=1#comment108681104_61437030 – Odinn Apr 26 '20 at 08:15
  • Welcome to the world of asynchronously retrieved results in Javascript. You too get to go through the initiation process of learning about asynchronous, non-blocking operations and functions that return before your asynchronous result is ready. For a discussion of your options to solve this, study this: [How do I return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323) which is exactly what you have here. Hint, you will need to use a callback, a promise or an event. – jfriend00 Apr 26 '20 at 08:23

0 Answers0