我试图使和alexa技能,阅读我创建的API。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>。
我认为这与作用域有关,但无法确定为什么文本在log b中是正确的,但在d中不正确。如果我不能在resonoce.on中使用this.emit (‘resonoce.on’),那么我需要一种方法来从那里获取信息,以便在最后使用。
发布于 2017-12-29 18:06:16
你被卡住的原因是因为异步函数。https.get是一个异步函数,这意味着代码将继续执行,当https.get返回响应时,将执行回调函数。理想情况下,无论您想要对响应做什么,都应该在回调函数中。
文本变量的原始值是The session will be。然后执行https.get,因为它是异步的,所以将在https.get之后执行其他代码行,并执行console.log("d" + text);文本的值仍然保持不变,并打印旧值。现在,https.get返回了一个成功的响应并触发了回调,现在文本值发生了变化,因此console.log("b" + text);可以看到新值
https://stackoverflow.com/questions/48020692
复制相似问题