我试图学习并使用异步 - 等待 - 承诺,但我收到语法错误"未定义的令牌功能"指的是我定义异步函数的行。我检查了一个开放式支架,但它们看起来都很好。
我如何让它工作?
------更新-----
- 处理程序被解雇 -
const NumberIntentHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& handlerInput.requestEnvelope.request.intent.name === 'NumberIntent';
},
async handle(handlerInput) {
let slotNum = handlerInput.requestEnvelope.request.intent.slots.number.value;
//var myRequest = parseInt(slotNum);
const myRequest = parseInt(slotNum);
console.log('NumberIntentHandler myRequest: ', myRequest);
const options = `http://numbersapi.com/${myRequest}`;
console.log('NumberIntentHandler options: ', options);
// Use the async function
const myResult = await httpGet(options)
console.log("sent : " + options);
console.log("received : " + myResult);
const speechText = myResult;
console.log('speechText: ', speechText); // Print the speechText */
return handlerInput.responseBuilder
.speak(speechText)
.withSimpleCard('Here is your fact: ', speechText)
.getResponse();
},
};
- 从处理程序调用的函数 -
async function httpGet(options) {
// return new pending promise
console.log(`~~~~~~~~ httpGetPromise ~~~~~~~~~`);
console.log(`~~~~~~~~~~~~~~~~${JSON.stringify(options)}~~~~~~~~~~~~~~`);
return new Promise((resolve, reject) => {
const request = http.get(options, (error, response, body) => {
// handle http errors
if (response < 200 || response > 299) {
reject(new Error('Failed to load page, status code: ' + response));
}
});
// handle connection errors of the request
request.on('error', (err) => reject(err));
request.end();
});
}
错误记录我