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

感情迁移 提交于 2019-12-25 09:25:50

问题


I am making an API request and would like to ask the user a question with the data returned from the request. 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. How can I wait for the request callback to be executed and then issue the :ask event?


回答1:


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.

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



回答2:


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


来源:https://stackoverflow.com/questions/44076217/aws-lambda-node-js-execute-this-emit-after-async-http-request-completes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!