[英]Running Async functions in Microsoft Bot Builder (with Node.JS)
I'm trying to make a test bot that, upon being chatted to responds with a (meaningless) string gotten from a JSON object through another API 我正在尝试创建一个测试机器人,通过聊天来响应从JSON对象通过另一个API获得的(无意义的)字符串
Code: 码:
var restify = require('restify');
var builder = require('botbuilder');
var request = require('request-promise');
// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
// Create chat connector for communicating with the Bot Framework Service
var connector = new builder.ChatConnector({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
// Listen for messages from users
server.post('/api/messages', connector.listen());
// Receive messages from the user and respond by echoing each message back (prefixed with 'You said:')
var bot = new builder.UniversalBot(connector, function (session) {
var text = await MyRequest()
session.send("%s", text);
});
async function MyRequest() {
var options = {
uri: "https://jsonplaceholder.typicode.com/posts/1",
method: "GET",
json: true
}
try {
var result = await request(options);
return result;
} catch (err) {
console.error(err);
}
}
The problem is the bot var isn't an asynch function, so I can't put await in it. 问题是bot var不是异步函数,所以我不能等待它。 If I remove await, the bot replies with Object Promise.
如果我删除await,则bot会回复Object Promise。 I'm fairly inexperienced in JS overall, so can I get any pointers?
我在JS整体上相当缺乏经验,所以我能得到任何指示吗?
e: The Request part works great, I've tested it alone in a different js program e:请求部分工作得很好,我已经在不同的js程序中单独测试了它
Have you tried this. 你试过这个吗? If you are using ES6 compatible Node environment this should work
如果您使用ES6兼容节点环境,这应该工作
var bot = new builder.UniversalBot(connector, async function (session) {
// Use JSON.stringify() if MyRequest Promise will resolve a object
var text = await MyRequest()
session.send("%s", text);
});
If async/await
isn't possible, how about returning a promise? 如果无法执行
async/await
,那么返回一个promise怎么样? like below: 如下:
function MyRequest() {
var options = {
uri: "https://jsonplaceholder.typicode.com/posts/1",
method: "GET",
json: true
}
return request(options);
}
And use Promise.then
to act on the result, like so: 并使用
Promise.then
对结果进行操作,如下所示:
var bot = new builder.UniversalBot(connector, function (session) {
MyRequest().then(function(text) {
session.send("%s", text);
}).catch(function(error) {
session.send("%s", error);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.