我尝试等待一个函数返回我的mysql表的值,并将其用作我的const ProjektNameIntentHandler的返回值。这是我的代码:
const ProjektNameIntentHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& handlerInput.requestEnvelope.request.intent.name === 'ProjektNameIntent';
},
handle(handlerInput) {
let getProjektName = queryDb()
getProjektName.then(function(result) {
var projektName = result[0];
console.log(projektName.Test);
})
return handlerInput.responseBuilder
.speak(projektName.Test)
.withSimpleCard('Venture', projektName.Test)
.getResponse();
}
};
现在的问题是,在ProjektNameIntentHandler
得到结果之前先得到projektName
的结果。首先,我尝试将第二个返回值放到函数范围内。但是通过这种方式,结果也属于功能,而不是作为我的ProjektNameIntentHandler
的回报。
所以我要做的只是归档handlerinput
的第二次返回,等待我的getProjektName.then
完成。我该怎么办?
答案 0 :(得分:0)
您确实已经猜到,到目前为止,由于异步函数undefined
尚未解析,您将返回getProjektName
。关键是,在同步函数内部,您不能等待以使函数完成执行-您只能在异步函数中执行此操作……但是,您可以使handle
异步!如果符合您的要求,则可以这样修改代码:
const ProjektNameIntentHandler = {
// ...
async handle(handlerInput) { // 'async' makes the function asynchronous
let result = await queryDb(); // wait for the promise to resolve
let projektName = result[0];
console.log(projektName.Test);
return handlerInput.responseBuilder
.speak(projektName.Test)
.withSimpleCard('Venture', projektName.Test)
.getResponse();
}
};
我将跳过关于如何接受JavaScript异步性的冗长解释-已经有similar question with a high-quality answer可以做到这一点!