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

如何使用上下文变量将信息传递给JavaScript中的Promise函数?,javascript,jquery,Javascript,Jquery,这里的用例是,我希望能够用另一个来源(比如文本框)的输入填充“content”的值。因此,用户可以输入一些文本点击“分析”,然后它将在帖子正文中发送文本并显示返回。我已经能够在R和Python中实现这一点,但现在我试图了解如何在Javascript中实现这一点 我试图将一个变量传递到JavaScript中的Promise/.thenable函数中。我正在粘贴下面的示例代码。我想能够做的是传递函数start一个变量作为JSON的内容部分,特别是 我想更改函数的这一部分: return gapi.c

这里的用例是,我希望能够用另一个来源(比如文本框)的输入填充“content”的值。因此,用户可以输入一些文本点击“分析”,然后它将在帖子正文中发送文本并显示返回。我已经能够在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.'
    }
});
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);
  }
};
对这样的事情:

return gapi.client.language.documents.analyzeSentiment({
    'document': {
        'type': 'PLAIN_TEXT',
        'content': thisIsTheTextToAnalyze
    }
});
我读过一些关于上下文传递的内容。根据我在那里读到的内容,我认为我必须修改代码,以便它使用

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>

函数start(){
//使用API密钥和Translate API初始化客户端。
gapi.client.init({
“apiKey”:myApiKey,
“discoveryDocs”:['https://language.googleapis.com/$discovery/rest?版本=v1'],
}).然后(函数(){
//执行API请求,并返回承诺。
//方法名'language.translations.list'来自API发现。
//gapi.client.language.translations.list
//方法=注释文本
返回gapi.client.language.documents.analyzeTouction({
“文件”:{
“类型”:“纯文本”,
“内容”:当我带孩子们去公园时,我和他们玩得很开心
}
});
})。然后((结果)=>{
const情绪=results.result.document情绪;
警惕(`文件情绪:`);
警惕(`Score:${touction.Score}`);
警惕(`magnity:${moother.magnity}`);
常量句子=results.result.句子;
句子。forEach((句子)=>{
警报(`SENTRANCE:${SENTRANCE.text.content}`);
警觉(`Score:${session.touction.Score}`);
警惕(`magnity:${session.touction.magnity}`);
});
});
返回值(documenttouction.score);
};
//加载JavaScript客户端库,然后调用'start'。
//gapi.load('client',start);
$(函数(){
// ...
});
根据Aaron的一些建议,我尝试了

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

功能启动(内容){
返回函数()
{
gapi.client.init({
“apiKey”:Dontchhawish你知道,
“discoveryDocs”:['https://language.googleapis.com/$discovery/rest?版本=v1'],
}).然后(函数(){
返回gapi.client.language.documents.analyzeTouction({
“文件”:{
“类型”:“纯文本”,
“内容”:内容
}
});
})。然后((结果)=>{
const情绪=results.result.document情绪;
警惕(`文件情绪:`);
警惕(`Score:${touction.Score}`);
警惕(`magnity:${moother.magnity}`);
})
返回值(documenttouction.score);
}
};
//加载JavaScript客户端库,然后调用'start'。
$(函数(){
load('client',start('this not work'));
}
)
start
函数由另一个
gapi
函数调用…
gapi.load('client',start)
。以这种方式调用时,无法传递参数值

返回一个函数:

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.'
    }
});
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.'));
// No change!

最好先执行一次
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);
    }
  }
})();
用法:

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

当然,只要用范围内的变量替换常量字符串并具有预期值,它就会工作。这与承诺或“上下文”无关“或者别的什么。嘿,Bergi,这是一个很好的答案,除了我是一个javascript新手,所以我不理解本例中“范围”的概念。例如,你是说我可以将其设置为全局变量吗?是的,如果你想将其传递给调用,可以设置为局部变量,也可以设置为
start
的参数。不,这不起作用(或者我不知道如何使其起作用?)。start函数由另一个名为gapi.load的gapi函数调用,该函数的执行方式如下:gapi.load('client',start)。以这种方式调用时,无论如何都无法传递参数值。我会把这个加到原始问题上。啊,我现在明白了。您想调用
gapi.load('client',start)多次,但每次都在
开始中使用不同的
内容
?是的,完全正确。或者老实说,最好先初始化一次,然后为start传递不同的值。但是,是的。我已经试着实施你的建议,但我无法使它发挥作用。我将粘贴我在上面问题部分中提交的完整代码以进行更新。
返回函数(内容){…}
是另一种解决方案-您必须替换整个
开始部分。
。顶部部分起作用了吗?