繁体   English   中英

异步HTTP请求完成后,AWS Lambda Node.js执行this.emit

[英]AWS Lambda Node.js execute this.emit after async HTTP request completes

我正在提出一个API请求,并想问用户一个从请求返回的数据的问题。 我调用一个函数,该函数执行请求并返回适当的响应:

httpRequest(params).then(function(body) {
  console.log(body);
  this.emit(':ask', speechOutput, repromptSpeech);
});

this.emit函数返回未处理的promise拒绝错误。 如何等待请求回调执行,然后发出:ask事件?

this承诺内处理程序是不一样的this之外呢,所以我觉得未处理的承诺,拒绝可能会说, this.emit不是一个函数。

一个快速的解决方案是使用箭头函数 ,这可能就是为什么您自己的答案中的代码也能起作用的原因:

// `this` here...
httpRequest(params).then(body => {
  console.log(body);
  this.emit(':ask', speechOutput, repromptSpeech); // ...is the same as `this` here
}).catch(error => {
  console.error('uh-oh!', error);
});

我最终使用请求库解决了这个问题:

function getEntries() {
  return request.get('https://wezift.com/parent-portal/api/entries.json');
}

getEntries().then(
  (response) => {
    console.log(response);
    this.emit(':ask', 'hi', 'hi again');
  },
  (error) => {
      console.error('uh-oh! ' + error);
  }
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM