【问题标题】:How to correctly access the Amazon comprehend API with JavaScript Callback)如何使用 JavaScript 回调正确访问 Amazon Comprehend API)
【发布时间】:2021-03-19 03:09:51
【问题描述】:

我正在尝试访问 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 回调函数的结果?

【问题讨论】:

    标签: javascript amazon-web-services aws-lambda amazon-comprehend


    【解决方案1】:

    您可以在 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 函数。

    【讨论】:

      猜你喜欢
      • 2019-07-21
      • 1970-01-01
      • 2021-12-30
      相关资源
      最近更新 更多