Add async
关键字到handle
方法名称及用途await
inside:
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);
}