0

我正在尝试访问 Amazon Comprehend API 来检测句子的情绪分数。但我不知道如何从回调中正确访问 API 调用后的结果:

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;
}

如何存储 JavaScript 回调函数的结果?

4

1 回答 1

0

您可以在 NodeJS 中使用 async-await 语法。

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
    }
}

请注意,完整的功能需要是一个async功能。

于 2020-12-07T19:51:22.937 回答