【问题标题】:AWS Lambda Node.js execute this.emit after async HTTP request completesAWS Lambda Node.js 在异步 HTTP 请求完成后执行 this.emit
【发布时间】:2017-10-19 22:45:15
【问题描述】:

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

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

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

【问题讨论】:

  • 你能提供这个文件的完整代码吗?包括您代码中的所有库等,以便我们知道您是否使用内置的http 库来发出请求以及您的事件发射是否是通过网络套接字等。如果this.emit 返回一个承诺,什么以下输出,this.emit(':ask', speechOutput, repromptSpeech).catch(console.log)?

标签: javascript aws-lambda


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    promise 处理程序内部的this 与外部的this 不同,所以我认为未处理的promise 拒绝可能表明this.emit 不是一个函数。

    一个快速的解决方案是使用arrow function,这可能就是您自己答案中的代码也可以工作的原因:

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

    【讨论】:

      猜你喜欢
      • 2018-06-21
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多