1

I try to wait for a function to return a value of my mysql table, and use this as a return for my const ProjektNameIntentHandler. This is my code:

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();
    }
};

Now the problem is that get the result of ProjektNameIntentHandler before projektName got the result. First, I tried to put the second return into the scope of the function. But in this way, the result also belongs to the funtion and not as a return for my ProjektNameIntentHandler.

So all I try do archieve is that the second return for the handlerinput, waits for my getProjektName.then to finish. How can I do that?

Nino Filiu
  • 16,660
  • 11
  • 54
  • 84
Olli
  • 13
  • 3

1 Answers1

0

As you indeed guessed, as of now, you return undefined because the asynchronous function getProjektName has not yet resolved. The thing is, inside a synchronous function, you can't wait for a function to finish executing - you can only do that in asynchronous functions... However, you could make handle asynchronous! If that fits your requirements, you can modify your code as such:

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();
    }
};

I'll skip the lengthly explanations of how to embrace the asynchronicity of JavaScript - there's already a similar question with a high-quality answer that does just that!

Nino Filiu
  • 16,660
  • 11
  • 54
  • 84
  • OMG IT FINALLY WORKS! Thank you so so much! I was brachiate through soooo many different methods and nothing worked. I cant beliefe it finaly came to an end! – Olli Mar 24 '19 at 14:45
  • Great! I'm happy to hear that! By the way - it can feel weird for new users, but *thank-you comments* should be avoided, instead, simply upvote and/or accept the question - [here's why](https://stackoverflow.com/help/someone-answers). Happy coding @0lli1234! – Nino Filiu Mar 24 '19 at 14:50