2017-05-19 129 views
0

我正在发出一个API请求,并希望向用户询问从请求返回的数据。我打电话给一个函数,它执行的请求,并返回相应的响应:AWS Lambda Node.js在异步HTTP请求完成后执行this.emit

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

的this.emit函数返回一个未处理的承诺废品。如何等待请求回调被执行,然后发出:ask事件?

+0

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

回答

2

承诺处理器内部的this是不一样的this之外的,所以我觉得未处理的承诺,拒绝可能会说,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); 
}); 
+0

太棒了,谢谢! –

0

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

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