【发布时间】:2019-10-14 09:51:19
【问题描述】:
我对 promises、async/await 和 Alexa/lambda 不熟悉,所以请耐心等待。
我的函数在返回数据之前返回。我遇到了一个类似的问题,我遇到了一个错误,但后来我对我的函数进行了相当多的编辑,因此提出了一个新问题。我现在不再收到错误,而是首先返回我的数据,然后执行 promise。
在阅读了许多 SO、google 和 amazon 开发者论坛后,我尝试重新编写 promise/function。似乎没有什么对我有用。
const IntentRequest = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest';
},
async handle(handlerInput) {
const { requestEnvelope, serviceClientFactory, responseBuilder } = handlerInput;
let responseData, promise;
checkAuthenticationStatus(handlerInput,function(json){
console.log('waited!')
if(json.error) {
return handlerInput.responseBuilder.speak(messages.NO_ACCESS).withSimpleCard('Unauthorized Request', messages.NO_ACCESS).getResponse();
} else if(json.noerror && json.noerror.okay == 'true'){
console.log('starting to get intent data')
const url = new URL(json.noerror.okay.path);
promise = new Promise((resolve, reject) => {
console.log('start promise')
return httpsGetIntent(handlerInput, url).then((resultData) => {
console.log(resultData)
responseData = resultData;
resolve(responseData)
console.log('inside promise, no error, prior to return data')
})
}).then((result) => { console.log('result', result)})
return handlerInput.responseBuilder.speak('Test').getResponse();
}
});
console.log('response data', responseData)
let result = await promise;
return result;
},
};
在我为调试添加的许多 console.logs() 中,它们打印如下: - '响应数据' - “等待!” - '开始获取意图数据' - '开始承诺' - 结果数据 - '内部承诺,没有错误,在返回数据之前'
【问题讨论】:
-
正如所写,
return handlerInput.responseBuilder.speak('Test').getResponse();不在 .then 回调中,尽管缩进使它看起来不是这样。还有其他问题需要解决。 -
感谢@Roamer-1888!我昨晚实际上解决了这个问题,并且即将发布我的答案。
标签: node.js lambda promise alexa alexa-skills-kit