如何正确使用Alexa技能内的异步功能?

时间:2020-06-04 03:56:08

标签: alexa alexa-skills-kit alexa-skill alexa-sdk-nodejs

我对异步编程非常陌生,因此请原谅我缺乏了解,但是我目前正在构建一种Alexa技能,该技能称为私有停车API。您可以调用此API,它将为您提供最近的停车位。

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

理想情况下,一旦我添加代码以修改useTheResult中的响应,我也希望问题代码也位于useTheResult中...为什么?因为一旦我选择了想要的数据并对其进行了修改,我将尝试将其变成“ Alexa可读”的句子,例如:

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

如果我现在就这样做,那么在Alexa控制台中对其进行测试时会出现错误。我不知道该怎么办,我感觉自己将陷入异步函数的无限循环中。

1 个答案:

答案 0 :(得分:0)

async方法名称中添加handle关键字,并在其中使用await

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

            // Call to the API
             let result = null;
             try {
                 const response = await axios.post(API_URL, requestData, options);
                 result = response.data.result;
             } catch(error) {
                 // handle this case and return some message to User
                 console.log(error);
             }
            
            // assume your data structure to be like:
            /**
             result: {
               roadName1: "1st street",
               roadName2: "2nd street",
               roadName3: "3rd street", 
               startingPrice: "1.2"
             }
            */
            const {roadName1, roadName2, roadName3, startingPrice} = result;

            // This is what we will refer to the 'problem code'.
            let say = `Hello from confidentialCompany! You can park on ${roadName1}, ${roadName2} and ${roadName3}. Prices start from ${startingPrice} pounds.`;
                return responseBuilder
                    .speak(say)
                    .reprompt('try again, ' + say)
                    .getResponse();
        },
    };

如果您要在同一函数中进行更多调用:

try {
   const [response1, response2] = await Promise.all([
      axios.post(API_URL1, requestData, options),
      axios.post(API_URL2, requestData, options)
   ]);
   // do things with your responses
   // ...
} catch(error) {
   // handle this case and return some message to User
   console.log(error);
}