0

I'm trying to return a string value of an object generated by aws translate, the structure's object is

{
 TranslatedText: "Hola", 
 SourceLanguageCode: "en", 
 TargetLanguageCode: "es"
}

the function

    this.translate.translator.translateText(params, (err, data) => {
      if (err) {
        console.log(err, err.stack)
        return err.stack;
      } 
      if(data) { 
        console.log("translation :");
        console.log(data.TranslatedText);
        return data.TranslatedText;
      }
    });

I can see the string in console, but it is not returning it.

I think that I'm misunderstanding some async job here, and maybe the returned value is actually getting an undefined, but I'm not clear.

3 Answers3

0

As it is in a callback function, so you won't be able to return the data like the way you are doing. Try using promises instead.

Nikhil Goyal
  • 1,945
  • 1
  • 9
  • 17
0

If doesn't make sense to return values from callbacks. Do what you want to do with the return value inside your callback.

Bloatlord
  • 385
  • 3
  • 8
0

Sounds like translateText is an async function. Therefore, await it like so:

this.translate.translator.translateText(params, (err, data) => {
      if (err) {
        console.log(err, err.stack)
        return err.stack;
      } 
      if(data) { 
        console.log("translation :");
        console.log(data.TranslatedText);
        return data.TranslatedText;
      }
    });
ViqMontana
  • 5,090
  • 3
  • 19
  • 54