Мой обработчик javascript использует вызов API и возвращает текстовую строку (тело), которая присваивается const speechText
.Но, как вы можете видеть из результатов журнала, сначала speechText выдает ошибку, потому что он не определен, но когда вызывается метод request.get
, он, похоже, вернул правильный результат.
Является ли это асинхронной проблемой, иесли да, то как мне реструктурировать код, чтобы получить результат (тело), когда он мне нужен?Я думаю, что код выполняет return handlerInput.responseBuilder
, прежде чем результат возвращается из вызова API.
Вот мой код:
const NumberIntentHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& handlerInput.requestEnvelope.request.intent.name === 'NumberIntent';
},
handle(handlerInput) {
console.log('At NumberIntentHandler');
let slotNum = handlerInput.requestEnvelope.request.intent.slots.number.value;
const url = `http://numbersapi.com/${slotNum}`;
console.log('url: ', url);
request.get(url, (error, response, body) => {
console.log('error: ', error); // Print the error if one occurred
console.log('statusCode: ', response && response.statusCode); // Print the response status code if a response was received
console.log('body: ', body); // Print the body
const speechText = body;
console.log('speechText: ', speechText); // Print the speechText
});
return handlerInput.responseBuilder
.speak(speechText)
.withSimpleCard('Here is your fact: ', speechText)
.getResponse();
}
};
![Log results](https://i.stack.imgur.com/4f9bZ.png)