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