1

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

2
  • 2
    Possible duplicate of How do I return the response from an asynchronous call? Commented Oct 1, 2017 at 4: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. Commented Oct 1, 2017 at 4:30

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.