Is there a good brief example of calling async code from a Jovo Intent handler?


#1

(Apologies if this has already been answered; I did a quick search but haven’t found it yet if so.)

Jovo intent handling code in Javascript is written as if it is synchronous, at least in the examples I’ve seen.

Unfortunately Javascript insists on doing some things, such as network I/O, asynchronously via promise chains (or async/await, which is syntactic sugar for the same thing). There appears to be no clean way to have a synchronous operation wait for async to complete before proceeding. (There are – or claim to be – implementations of mutex semaphores, but those mostly involve spin loops with timeouts, which is Just Plain Ugly.)

As a Javascript novice, it really isn’t obvious to me how best to structure a Jovo handler which needs to get results from async operations. Given that others are using Jovo successfully, I assume it is possible, but I’m not sure how to get there from here.

Can anyone point me to a Best Practice / coding pattern I can adopt for rewriting my prototype synchronous intent handler into the needed async/promise form?

(In my case, I’m updating local structures from a database, which COULD run as a scheduled event spinning completely separately from the handlers, so I have a workaround. But that won’t always be an acceptable solution, eg when the network interaction has to tell the user whether it succeeded or failed. So I’d like to understand the general solution. Presuming there is one.)


#2

For a pure Alexa example, the advice seems to be just go ahead and declare the handler routine async and use await.

I’m just not sure the same is true for the Jovo environment.


#3

Yes, this is what we recommend as well in this tutorial:

app.setHandler({
    LAUNCH() {
        return this.toIntent('QuoteIntent');
    },

    async QuoteIntent() {
        const quote = await getRandomQuote();
        console.log(quote);

        this.tell(quote);
    },
});

#4

Thanks. As I said, I’m still getting used to Javascript’s quirks, and while this solution makes sense in hindsight I just wasn’t quite seeing it.

A few more tweaks, and I may be ready to declare version 1.0 of this beast. Still sanity checking permission on the unpublished APIs, considering swapping in a real database, and I need to move it to a server other than my desktop, but functionally it has a respectable set of features with only a few known issues. Rah.


#6

… Yeah, that seems to be working for me. I saw some odd behavior until I added the await as well as the async, but I’m chalking that up to user error.