我尝试等待函数返回 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();
}
};
现在的问题是,在 projektName
得到结果之前就得到了 ProjektNameIntentHandler
的结果。首先,我尝试将第二个 return 放入函数的范围内。但这样,结果也属于函数,而不是作为我的 ProjektNameIntentHandler
的返回。
因此,我尝试做的所有操作都是 handlerinput
的第二次返回,等待我的 getProjektName.then
完成。我怎样才能做到这一点?
最佳答案
正如您所猜到的,到目前为止,您返回了 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就是这样!
关于javascript - aasy 函数结束后返回函数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55324712/