0

I am trying to return a value extracted from within a .then call in a javascript function (please excuse me if I'm using the incorrect terminology, and please correct me so I can learn). Here is the code that I am working with

function analyzeSentimentOfText (text) {
  // [START language_sentiment_string]
  // Imports the Google Cloud client library
  const Language = require('@google-cloud/language');
  // Instantiates a client
  const language = Language();

  // The text to analyze, e.g. "Hello, world!"
  // const text = 'Hello, world!';

  const document = {
    'content': text,
    type: 'PLAIN_TEXT'
  };


  // Detects the sentiment of the document
  language.analyzeSentiment({ document: document }) 

    .then((results) => {
      const sentiment = results[0].documentSentiment;

      console.log(`Document sentiment:`);
      console.log(`  Score: ${sentiment.score}`);
      console.log(`  Magnitude: ${sentiment.magnitude}`);

    })
    .catch((err) => {
      console.error('ERROR:', err);
    });
  // [END language_sentiment_string]
}

What I want to accomplish is extract the sentiment score (and ideally also the magnitude) for results[0].documentSentiment.sentiment.score.

What I've tried to do is this

function analyzeSentimentOfText (text) {

  const Language = require('@google-cloud/language');
  const language = Language();
  const document = {
    'content': text,
    type: 'PLAIN_TEXT'
  };

  language.analyzeSentiment({ document: document }) 

    .then((results) => {
      const sentiment = results[0].documentSentiment;
      return sentiment.score;
    })
    .catch((err) => {
      console.error('ERROR:', err);
    });
  // [END language_sentiment_string]
}

Can anyone help me out? Or do I have to totally change the approach?

Thanks, Brad

Sven
  • 4,653
  • 26
  • 49
Brad Davis
  • 919
  • 3
  • 15
  • 34
  • 2
    Possible duplicate of [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) – Hassan Imam Oct 01 '17 at 04:05
  • The short answer is you can't do that. Promises are just sugar to make callbacks less convoluted and deeply nested. The whole thing is asynchronous and no way out of it. You can never `return` the value, you must instead define a function that you want to run whenever said value is actually ready. Even `async/await` which lets you write what _looks_ more like old-school synchronous code, is just even more sugar on top of promises. The `await` key word effectively defines the code below it as the callback. Every `async\await` function returns a promise, never just a raw value. – skylize Oct 01 '17 at 04:30

2 Answers2

1

Unfortunately you can't return the exact value, but you can return the Promise. This means that the function analyzeSentimentOfText will return a Promise that resolves to a value, rather than an actual value.

Like so:

function analyzeSentimentOfText (text) {

  const Language = require('@google-cloud/language');
  const language = Language();
  const document = {
    'content': text,
    type: 'PLAIN_TEXT'
  };

  return language.analyzeSentiment({ document: document }) 
    .then(results => results[0].documentSentiment.score);
  // [END language_sentiment_string]
}

Which will then be used like this:

analyzeSentimentOfText("sometext")
  .then((score) => {
    console.log(score); // Whatever the value of sentiment.score is
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

If you target Node v7.6 or above, you can utilize async/await:

async function analyzeSentimentOfText (text) {
  const Language = require('@google-cloud/language');
  const language = Language();
  const document = {
    'content': text,
    type: 'PLAIN_TEXT'
  };

  return (
    await language.analyzeSentiment({ document: document })
  )[0].documentSentiment.score
}

(async () => {
  try {
    let score = await analyzeSentimentOfText("someText");
  } catch (err) {
    console.error('ERROR:', err);
  }
})();

The reason the above has an async immendiately-invoked function is because await can only be used within an async function.

Sven
  • 4,653
  • 26
  • 49
0

Have you tried:

function analyzeSentimentOfText (text) {

const Language = require('@google-cloud/language');
const language = Language();
const document = {
  'content': text,
  type: 'PLAIN_TEXT'
};

return language.analyzeSentiment({ document: document }) 
  .then((results) => {
    const sentiment = results[0].documentSentiment;
    return sentiment.score;
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });
// [END language_sentiment_string]