0

As described in watson-developer-cloud, I am using the following code to translate some text:

var watson = require('watson-developer-cloud');

var language_translation = watson.language_translation({
  username: '<username>',
  password: '<password>',
  version: 'v2'
});

var myTranslation = {};//is supposed to hold the translation provided by the following code:

language_translation.translate({
text: 'A sentence must have a verb', source : 'en', target: 'es' },
function (err, translation) {
  if (err)
    console.log('error:', err);
  else{
    myTranslation = JSON.stringify(translation, null, 2);
    console.log(myTranslation);//print out the JSON with translation data
  }
});
Here Begin problems:
console.log(myTranslation); // Print out an empty hash...

Why is myTranslation holding the right data inside the else statement, but outside it, it holds an empty hash?

Omar Lahlou
  • 1,000
  • 9
  • 33
  • Because the translation is not done yet when it reaches that point. –  Jan 25 '16 at 03:44
  • How do I implement an asynchronous call? – Omar Lahlou Jan 25 '16 at 09:50
  • 1
    There is nothing wrong with how you have implemented it. It is simply that the result is not available until it is available, within the callback. Anything you want to do with the result must be done within the callback, where it is available. –  Jan 25 '16 at 14:07

0 Answers0