我正在尝试制作和阅读我创建的API的alexa技能。 API工作正常并返回
{
"_id": "5a4523104494060cf097c1ad",
"description": "Sprinting",
"date": "2017-12-29"
}
我有以下代码
'getNext': function() {
var url = '***API ADDRESS*** ';
var text = "The session will be";
https.get(url, function(response) {
var body = '';
response.on('data', function(x) {
body += x;
});
console.log("a" + text);
response.on('end', function() {
var json = JSON.parse(body);
text += json.description;
console.log("b" + text);
this.emit(":tell", text);
});
console.log("c " + text);
});
console.log("d" + text);
// this.emit(":tell", text);
}
哪个控制台输出
2017-12-29T09:33:47.493Z dThe session will be
2017-12-29T09:33:47.951Z aThe session will be
2017-12-29T09:33:47.952Z c The session will be
2017-12-29T09:33:48.011Z bThe session will beSprinting
但是,这将为this.emit函数返回null。
如果我评论出来并取消注释另一个我得到一个<speak> The session will be</speak>
返回。
我认为与范围有关,但是无法确定为什么文本在日志b中是正确的而在d中没有。如果我不能在resonoce.on('end')中使用this.emit那么我需要一种方法来获取信息,以便在最后使用。
您遇到困难的原因是异步功能。 https.get
是一个异步函数,意味着代码将继续执行,当https.get返回响应时,将执行回调函数。理想情况下,无论您想对响应做什么,都应该在回调函数中。
您的文本变量的原始值是The session will be
。然后你执行https.get
,因为它的异步,将移动到https.get
之后执行其他代码行并执行console.log("d" + text);
文本的值仍然保持不变并打印旧值。现在https.get
返回一个成功的响应并触发回调,现在文本值已更改,因此console.log("b" + text);
看到新值