我对async编程非常陌生,所以原谅我的不理解,但我目前正在构建一个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控制台。我不知道该怎么做了,我感觉自己会陷入一个无限循环的异步函数中。
添加 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();
},
};