如何使用上下文变量将信息传递给JavaScript中的Promise函数?

时间:2017-10-08 06:05:06

标签: javascript jquery

这里的用例是我希望能够填补“内容”的价值。使用来自其他来源的输入,例如文本框。因此,用户可以输入一些文本点击"分析"然后它将文本发送到Post Body并显示返回。我已经能够在R和Python中使用它,但现在我试图了解如何在Javascript中使用它。

我正在尝试将变量传递给JavaScript中的Promise / .thenable函数。我粘贴下面的示例代码。我希望能够做的是传递函数start一个变量用作JSON的内容部分,特别是......

我想改变这部分功能:

return gapi.client.language.documents.analyzeSentiment({
    'document': {
        'type': 'PLAIN_TEXT',
        'content': 'I had a wonderful time with my children when I took them to the park.'
    }
});

这样的事情:

return gapi.client.language.documents.analyzeSentiment({
    'document': {
        'type': 'PLAIN_TEXT',
        'content': thisIsTheTextToAnalyze
    }
});

我已经阅读了有关从link传递上下文的内容。根据我在那里阅读的内容,我认为我必须改变代码,以便它使用

gapi.client.request 

方法而不是我在下面使用的方法 - 这只是使用

gapi.init, 
gapi.load, and 
gapi.client.language.documents.analyzeSentiment.  

这是对的吗?如果是这样,有人可以帮我弄清楚如何格式化

gapi.client.request 

函数调用还是指向文档解释一下?我不是一个javascript程序员而且我笨手笨脚,我无法找到解释它的任何演示。

这是完整的代码。

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://apis.google.com/js/api.js"></script>
<script>
  function start() {
    // Initializes the client with the API key and the Translate API.
    gapi.client.init({
      'apiKey': myApiKey,
      'discoveryDocs': ['https://language.googleapis.com/$discovery/rest?version=v1'],
    }).then(function() {

      // Executes an API request, and returns a Promise.
      // The method name `language.translations.list` comes from the API discovery.
      // gapi.client.language.translations.list
      // method = annotateText

      return gapi.client.language.documents.analyzeSentiment({
        'document': {
          'type': 'PLAIN_TEXT',
          'content': 'I had a wonderful time with my children when I took them to the park.'
        }
      });
    }).then((results) => {

      const sentiment = results.result.documentSentiment;
      alert(`Document sentiment:`);
      alert(`  Score: ${sentiment.score}`);
      alert(`  Magnitude: ${sentiment.magnitude}`);
      const sentences = results.result.sentences;
      sentences.forEach((sentence) => {
        alert(`Sentence: ${sentence.text.content}`);
        alert(`  Score: ${sentence.sentiment.score}`);
        alert(`  Magnitude: ${sentence.sentiment.magnitude}`);
      });
    });

    return(documentSentiment.score);
  };

  // Loads the JavaScript client library and invokes `start` afterwards.
  // gapi.load('client', start);
  $(function (){
    // ...
  });
</script>
</head>
<body>
  <div id="results"></div>
</body>
</html>

跟进亚伦的一些建议,我已经尝试了

    <html>
  <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://apis.google.com/js/api.js"></script>
    <script>
      function start(content) {
        return function ()
        {
        gapi.client.init({
          'apiKey': DontchaWishYouKnew,
          'discoveryDocs': ['https://language.googleapis.com/$discovery/rest?version=v1'],
        }).then(function() {
          return gapi.client.language.documents.analyzeSentiment({
            'document': {
                      'type': 'PLAIN_TEXT',
                      'content': content
                   }
          });
        }).then((results) => {


        const sentiment = results.result.documentSentiment;
        alert(`Document sentiment:`);
        alert(`  Score: ${sentiment.score}`);
        alert(`  Magnitude: ${sentiment.magnitude}`);

      })

        return(documentSentiment.score);

   }
    };

      // Loads the JavaScript client library and invokes `start` afterwards.
      $(function (){
         gapi.load('client', start('this doesnt work'));

      }
        )
    </script>
  </head>
  <body>
    <div id="results"></div>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

  

start函数由另一个gapi函数调用... gapi.load('client', start)。在以这种方式调用时,没有任何方法可以传递参数值。

返回一个函数:

function start(content) { // Called before being used as a parameter
  return function () { // Called by 'gapi.load' so no parameter passed
    gapi.client.init({
      // ...
    }).then(function() {
      // ...
      return gapi.client.language.documents.analyzeSentiment({
        'document': {
          'type': 'PLAIN_TEXT',
          'content': content
        }
      });
    }).then((results) => {
      // ...
    });

    return(documentSentiment.score);
  }
};

用法:

gapi.load('client', start('I had a wonderful time with my children.'));
gapi.load('client', start('A wonderful time with my children I had.'));
  

更好地执行init一次,然后能够为start传递不同的值。

范围:

var start = (function () { // Called immediately to scope (share) 'init'
  var init;
  return function (content) { // Called before being used as a parameter
    return function () { // Called by 'gapi.load' so no parameter passed
      if (!init) {
        init = gapi.client.init({
          // ...
        });
      }
      init.then(function() {
        // ...
        return gapi.client.language.documents.analyzeSentiment({
          'document': {
            'type': 'PLAIN_TEXT',
            'content': content
          }
        });
      }).then((results) => {
        // ...
      });

      return(documentSentiment.score);
    }
  }
})();

用法:

// No change!