1

我的代码没有运行,任何人都可以帮忙。无法说出文本,我可以返回处理程序输入响应吗?测试函数是一个 http 调用,可能需要 tieme。

function test(url, number)
{
    return 5;
}

function speak(handlerInput) {
    return handlerInput.responseBuilder
        .getResponse();
}

const NumberFactIntentHandler = {
    canHandle(handlerInput) {
        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'NumberFactIntent';
    },

    handle(handlerInput) {

    const theNumber = handlerInput.requestEnvelope.request.intent.slots.number.value;
    const repromptOutput = " Would you like another fact?";
    const URL = "http://numbersapi.com";

    test(URL, theNumber).then(function (data) {
             console.log("data is " + data);
             handlerInput.responseBuilder
            .speak("Test Data")
            .reprompt(repromptOutput) 

             return speak(handlerInput);
        }).catch(function (data) {

             console.log("error is " + data);
             handlerInput.responseBuilder
            .speak(`I wasn't able to find a fact for ${theNumber}` )
            .reprompt(repromptOutput)
             return speak(handlerInput);
        }); 
    }
};
4

2 回答 2

1

首先,您的test函数不会返回承诺。我不知道这是否是故意的,你只是削减了 api 调用代码以使其更简单,但如果你想then在它上面使用它应该返回一个 promise。

如果它在您的完整示例中返回一个承诺,那么您缺少的是在之前添加一个 return test。你也应该handlerInput从你的承诺中返回。代码应如下所示(我将删除一些不相关的代码):

const NumberFactIntentHandler = {
    canHandle(handlerInput) {},

    handle(handlerInput) {

    const repromptOutput = " Would you like another fact?";
    const URL = "http://numbersapi.com";

    return test(URL, theNumber).then(function (data) {
             return handlerInput.responseBuilder
                .speak("Test Data")
                .reprompt(repromptOutput) 
        }).catch(function (data) {
             return handlerInput.responseBuilder
                 .speak(`I wasn't able to find a fact for ${theNumber}` )
                 .reprompt(repromptOutput)
        }); 
    }
};

现在您可能想知道为什么需要那些return. 这是因为 JS 函数隐式返回undefined,所以在这种情况下你必须明确告诉函数应该返回什么handle。同样适用于 promise 的内部。

于 2019-09-23T18:41:22.693 回答
0

此代码可能对您有所帮助!!

 //use request for http call
 function fun(url) {
      return new Promise((resolve, reject) => {
       request.get(url,(err, res, body) => {
       console.log("url-fetched");
       return resolve(body);
     });
   });
  }

   const NumberFactIntentHandler = {
      canHandle(handlerInput) {..
      },

 async handle(handlerInput) {

   const theNumber =handlerInput.requestEnvelope.request.intent.slots.number.value;
   const repromptOutput = " Would you like another fact?";
   const URL = "http://numbersapi.com";
   let data = await fun(url);

   return handlerInput.responseBuilder
    .speak(data)
    .reprompt('is there any thing i can do for you?')
    .withSimpleCard('Hello', speechText)
    .getResponse();
  };
于 2019-09-24T14:17:47.237 回答