Return aasy 函数结束后函数的值

Return the Value of a function after aasy function ended

我尝试等待函数 return 我的 mysql table 的值,并将其用作我的 const ProjektNameIntentHandler 的 return。这是我的代码:

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.

的 return

所以我尝试做的就是 handlerinput 的第二个 return,等待我的 getProjektName.then 完成。我该怎么做?

果然如你所料,截至目前,你returnundefined因为异步函数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 可以做到这一点!