简体   繁体   English

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

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

I am making an API request and would like to ask the user a question with the data returned from the request. 我正在提出一个API请求,并想问用户一个从请求返回的数据的问题。 I make a call to a function, which executes the request and returns the appropriate response: 我调用一个函数,该函数执行请求并返回适当的响应:

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

The this.emit function returns an unhandled promise rejection error. this.emit函数返回未处理的promise拒绝错误。 How can I wait for the request callback to be executed and then issue the :ask event? 如何等待请求回调执行,然后发出:ask事件?

The this inside the promise handler isn't the same as this outside of it, so I think the unhandled promise rejection might have stated that this.emit isn't a function. this承诺内处理程序是不一样的this之外呢,所以我觉得未处理的承诺,拒绝可能会说, this.emit不是一个函数。

A quick solution would be to use an arrow function , which is probably why the code in your own answer works too: 一个快速的解决方案是使用箭头函数 ,这可能就是为什么您自己的答案中的代码也能起作用的原因:

// `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);
});

I ended up solving this using the request library: 我最终使用请求库解决了这个问题:

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