如果我调用doHttp函数,它将毫无问题地获取日志中的数据。我似乎无法让数据返回并可以说出来。我正在使用通过nodejs的Visual Studio代码。我对此很陌生,所以我知道我缺少一些东西。
const url = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY";
const linkIntentHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& handlerInput.requestEnvelope.request.intent.name === 'linkIntent';
},
handle(handlerInput) {
var data = doHttp();
var speechText = data;
return handlerInput.responseBuilder
.speak(speechText)
.withSimpleCard('Card title', speechText)
.getResponse();
},
};
function doHttp() {
var data2 = '';
https.get(url, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
data2 = JSON.parse(data).title;
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
return data2;
}
//Working function
function doHttp() {
https.get(url, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(JSON.parse(data).title);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}
答案 0 :(得分:0)
HTTP请求是一个异步函数,您的代码不会等待响应到来。 您可以将http functon调用包装在promise中并返回。然后可以在句柄输入功能中应用异步/等待。以下是使用天气API的示例代码。
const url =
"https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22";
const linkIntentHandler = {
canHandle(handlerInput) {
return (
handlerInput.requestEnvelope.request.type === "IntentRequest" &&
handlerInput.requestEnvelope.request.intent.name === "linkIntent"
);
},
async handle(handlerInput) {
const data = await doHttp();
console.log("data in handle input ", data);
const speechText = data;
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(speechText)
.withSimpleCard(speechText, speechText)
.getResponse();
}
};
function doHttp() {
var data2 = "";
return new Promise((resolve, reject) => {
https
.get(url, resp => {
let data = "";
// A chunk of data has been recieved.
resp.on("data", chunk => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on("end", () => {
console.log("data ", data);
data2 = JSON.parse(data).weather[0].description;
console.log("weather ", data2);
resolve(data2);
});
})
.on("error", err => {
console.log("Error: " + err.message);
});
});
}
使用以下链接可了解有关进行外部API调用的更多信息。 https://developer.amazon.com/blogs/alexa/post/4a46da08-d1b8-4d8e-9277-055307a9bf4a/alexa-skill-recipe-update-call-and-get-data-from-external-apis