1

我正在尝试进一步扩展 telegram-rocket.chat 桥,需要为此调用一些 api。为此,rocket.chat 公开了一个名为 HTTP 的 Meteor.js 包装器。

此代码片段是一个传出挂钩,它处理用户发送的消息,让我转换消息并传递更改后的文本。

prepare_outgoing_request({request}) 被 Rocket.chat 钩子调用,我想在其中调用一个 API,将表情符号代码解析为实际的表情符号字符:“:see_no_evil: to”

/** Global Helpers
 *
 * console - A normal console instance
 * _       - An underscore instance
 * s       - An underscore string instance
 * HTTP    - The Meteor HTTP object to do sync http calls
 *           https://docs.meteor.com/api/http.html
 */


class Script {
    request_emojitext(emoji_code) {
       console.log(`called: request_emojitext('${emoji_code}')`);
       const url = `https://www.emojidex.com/api/v1/emoji/${emoji_code}`;
  
       const response = HTTP.call('GET', url);

       console.log(`Emoji Response: ${response.constructor.name} => ${JSON.stringify(response)}`);
      // Emoji Response: Object => {"error":{}}             
       return response;
    }
  
    /**
    	request.params            {object}
     	request.method            {string}
    	request.url               {string}
    	request.headers           {object}
    	*/
    prepare_outgoing_request({ request }) {
      	const emojiResponse = this.request_emojitext('see_no_evil');
      	const emojiCharacter = emojiResponse.content.emoji;
        
        return {
          // https://core.telegram.org/bots/api
          url: `${request.url}&text=${emojiCharacter}`,
          method: 'GET'
        };
    }
}

Meteor 文档指出:

// Asynchronous call
Meteor.call('foo', 1, 2, (error, result) => { ... });

// Synchronous call
const result = Meteor.call('foo', 1, 2);

/*
On the client, if you do not pass a callback and you are not 
inside a stub, call will return undefined, and you will have 
no way to get the return value of the method. That is because
the client doesn’t have fibers, so there is not actually any 
way it can block on the remote execution of a method.
*/

我不确定如何在这里进行,因为我对异步编程还不完全满意。在结果实际可用之前,我将如何阻止,或者是否有另一种我完全想念的方法?

4

2 回答 2

1

Like the documentation says, there is no way to block on the client -- browsers simply don't implement any mechanism for that. So the question is what it is that makes it difficult for you to deal with the delay on the client until the callback is called. The typically pattern, of course, is to switch the client into some sort of "waiting" state when the call is made (e.g., show a spinner), and then update the page with the result when the callback fires (and hide the spinner).

于 2018-11-04T17:33:33.387 回答
1

我通过查看 HTTP 变量(PR #5876)的实现发现了问题。此外,已打开异步调用的功能请求(问题 #4775)。

const response = HTTP('GET', 'https://www.emojidex.com/api/v1/emoji/sweat_smile');

这会同步执行 API 调用并返回一个结果对象:

{
  "result": {
    "statusCode": 200,
    "headers": {
      // ...
    },
    "data": {
      "code": "sweat smile",
      "moji": "",
      // ...
    }
  }
}

如果您想查看完整代码,可以在 Git 上查看

于 2018-11-05T19:21:42.983 回答