簡體   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