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.