How to correctly access the Amazon comprehend API with JavaScript Callback)

493 views Asked by At

I am trying to access the Amazon comprehend API to detect the sentiment score of a sentence. But I don't know how to correctly access the results after the API call from out of the callback:

function getSentiment(text){
    console.log('old params.Text: '+JSON.stringify(params.Text));
    params.Text = text;
    console.log('new params.Text: '+JSON.stringify(params.Text));
    var result = comprehend.detectSentiment(params,function(err, data) {
        if (err) console.log(err, err.stack); // an error occurred
        else     sentiment = data.Sentiment; // successful response -> String mit Sentiment | "POSITIVE" "NEGATIVE" "NEUTRAL" "MIXED"
    });
    console.log('reslut of comprehend.detectSentiment: '+JSON.stringify(result));
    console.log('sentiment from the data object: '+JSON.stringify(sentiment));
    return sentiment;
}

How do I store the results from the JavaScript Callback Function?

1

There are 1 answers

0
Sarthak Jain On

You can use the async-await syntax in NodeJS.

exports.fn = async (event, context) {
    // Get params from event ....
    try {
      var data = await comprehend.detectSentiment(params).toPromise();
      // access data.sentiment here
    } catch (error) {
      // Handle error
    }
}

Note that the complete function needs to be an async function.