【问题标题】:Return the Value of a function after aasy function endedaasy函数结束后返回函数的值
【发布时间】:2019-03-24 14:15:33
【问题描述】:

我尝试等待一个函数返回我的 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 完成。我该怎么做?

【问题讨论】:

    标签: javascript node.js json alexa alexa-skills-kit


    【解决方案1】:

    正如您确实猜到的,到目前为止,您返回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 可以做到这一点!

    【讨论】:

    • 天哪,终于成功了!非常感谢你!我通过很多不同的方法获得了brachiate,但没有任何效果。我不能相信它终于结束了!
    • 太棒了!我很高兴听到这个消息!顺便说一句 - 新用户可能会觉得很奇怪,但应该避免thank-you cmets,而是简单地投票和/或接受问题 - here's why。快乐编码@0lli1234!
    猜你喜欢
    • 2015-08-08
    • 1970-01-01
    • 2018-07-01
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2021-11-09
    • 1970-01-01
    相关资源
    最近更新 更多