Невозможно обработать намерение Алексы - PullRequest
1 голос
/ 23 сентября 2019

Мой код не работает, кто-нибудь может помочь.Невозможно произнести текст, могу ли я вернуть ответ обработчика ввода.Тестовая функция - это http-вызов, который может занять время.

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);
        }); 
    }
};

Ответы [ 2 ]

1 голос
/ 23 сентября 2019

Прежде всего ваша функция test не возвращает обещание.Я не знаю, является ли это преднамеренным, и вы просто сокращаете код вызова API, чтобы сделать его проще, но он должен вернуть обещание, если вы хотите использовать then для него.

Если он возвращает обещание вВаш полный пример, то, что вы упускаете, это добавление возврата до 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.То же самое относится и к обещанию.

0 голосов
/ 24 сентября 2019

Этот код может помочь вам!

 //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();
  };
...