question

ImNewToThisSorry avatar image
ImNewToThisSorry asked

How to use async with the response builder?

I am very new to async programming, so forgive me for the lack of understanding and noobness, but I am currently building an Alexa skill which calls a private parking API. You can call this API and it will give you the nearest parking spots.

const getParkingSpots_Handler =  {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        return request.type === 'IntentRequest' && request.intent.name === 'getParkingSpots' ;
    },
    handle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        const responseBuilder = handlerInput.responseBuilder;
        let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
      
        let requestData = {
            // I can't show this sorry
            }
        
        let options = {
           // I can't show this sorry
        };
        
        // Call to the API
        const postAxios = async () => {
            try {
                const response = await axios.post(API_URL, requestData, options);
                return response.data.result;
            } catch(error) {
                console.log(error);
            }
        };
        
        // Another function. This is where I use the data from the API response. I intent to add some code here that only picks out a number of results, sorts it by price etc. etc.
        const useTheResult = async () => {
            const result  = await postAxios();
            console.log('Response from the API:', result);
        };
        
        // We defined the functions above, now we need to execute them
        useTheResult();

        // This is what we will refer to the 'problem code'.
        let say = `Hello from confidientialCompany! You can park...`;
            return responseBuilder
                .speak(say)
                .reprompt('try again, ' + say)
                .getResponse();
    },
};


Ideally once I add the code to modify the response within useTheResult, I want the problem code to be inside useTheResult as well...why? Because once I've picked out the data I want and modified it, I'll try to turn say into an 'Alexa-readable' sentence like:

let say = `Hello from confidentialCompany! You can park on ${roadName1}, ${roadName2} and ${roadName3}. Prices start from ${startingPrice} pounds.`

If I do that right now, as it is, I get an error when testing it out in the Alexa console. I have no idea what to do anymore, and I feel like I'm going to get stuck in an infinite loop of async functions.

Please...please help me.

alexa skills kitalexa voice servicealexaalexa simulator
10 |5000

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

Rokas avatar image
Rokas answered

Here is the blogpost that shows you how to call external apis and goes deeper into explaining how async works.


Looking at your example, your example, you're doing it a little bit incorrectly. This is what you need to do. Because you're going to do async call in handle function, you have to add 'async' before it. Then inside of it you can call 'axios' post right away and 'await' for the response from which you can take data etc and put it in you response.

const getParkingSpots_Handler =  {
    canHandle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        return request.type === 'IntentRequest' && request.intent.name === 'getParkingSpots' ;
    },
    async handle(handlerInput) {
        const request = handlerInput.requestEnvelope.request;
        const responseBuilder = handlerInput.responseBuilder;
        let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
     
        let requestData = {
            // I can't show this sorry
            }
        
        let options = {
           // I can't show this sorry
        };

      const response = await axios.post(API_URL, requestData, options);     

       console.log('Response from the API:', response.data.result)
 
 
        // This is what we will refer to the 'problem code'.
        let say = `Hello from confidientialCompany! You can park...`;
            return responseBuilder
                .speak(say)
                .reprompt('try again, ' + say)
                .getResponse();
    },
};


10 |5000

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.