Cheerio.load портит ответы на Google Assistant - PullRequest
0 голосов
/ 02 декабря 2018

У меня есть намерение с вызываемым cheerio.load (), и оно портится с ответами.Помощник Google постоянно говорит мне, что ответ не был задан, хотя позже в коде у меня есть ответы.Консоль также сообщает мне, что асинхронный вызов не был возвращен обработчику, который я считаю cheerio.load ().Можно ли как-нибудь это исправить, чтобы он продолжал искать правильный conv.ask внизу кода?Он все еще продолжает работать там, так как console.log (map) обнаруживается.Спасибо за любую помощь!

app.intent("late drop", (conv,{term,year}) => {
var date = new Date();
var month;
if(term == null){
    month = date.getMonth();

    if(month >= 9 && month <=12){
        term = "fall";
        //console.log("fall")
    }
    else if (month >= 1 && month <= 5) {
        term = "spring";
        //console.log("spring")
    }
    else {
        term = "summer";
        //console.log("summer")
    }
}
if(year == null){
    yearDig = date.getFullYear();
    year = yearDig;
    //console.log(year)
}
var strYear = year.toString();
var semester = term+strYear.substr(2);
const options = {
    uri: `https://www.registrar.psu.edu/academic_calendar/${semester}.cfm`,
    transform: function (body) {
        return cheerio.load(body);
  }
};
rp(options)
.then(($) => {
    let map = {};
    let columnOne = [];
    let columnThree = [];

    $('table').find('tr td:nth-child(1)').each(function (index, element) {
        columnOne.push($(element).text());
      });

    $('table').find('tr td:nth-child(3)').each(function (index, element) {
        columnThree.push($(element).text());
    });

    columnOne.forEach((item, i) => {
        map[item] = columnThree[i];
    });

    console.log(map);
    date = map["2Late Drop Begins"];
    conv.ask("The late drop period begins on " + map["2Late Drop Begins"])
})
.catch((error) => {
    console.log(error);
    conv.ask("An error occured, please try again.");
})

});

Ответы [ 2 ]

0 голосов
/ 02 декабря 2018

Проблема не в cheerio.

Похоже, вы используете request-promise или request-promise-native для выполнения HTTP-вызова.При этом выполняется асинхронная операция, которая возвращает обещание (о чем свидетельствует использование .then() и .catch().

, поскольку обработчики намерений, выполняющие асинхронные операции , должны вернуть обещание,вы можете просто вернуть тот, который возвращается цепочкой rp / then / catch. Что-то вроде изменения этой строки должно работать:

return rp(options)
0 голосов
/ 02 декабря 2018

Я изменил ваш код, чтобы вернуть Обещание.Проверьте, работает ли это для вас.

app.intent("late drop", (conv, {
  term,
  year
}) => {

  return new Promise(function (resolve, reject) {

    var date = new Date();
    var month;
    if (term == null) {
      month = date.getMonth();

      if (month >= 9 && month <= 12) {
        term = "fall";
        //console.log("fall")
      } else if (month >= 1 && month <= 5) {
        term = "spring";
        //console.log("spring")
      } else {
        term = "summer";
        //console.log("summer")
      }
    }
    if (year == null) {
      yearDig = date.getFullYear();
      year = yearDig;
      //console.log(year)
    }
    var strYear = year.toString();
    var semester = term + strYear.substr(2);
    const options = {
      uri: `https://www.registrar.psu.edu/academic_calendar/${semester}.cfm`,
      transform: function (body) {
        return cheerio.load(body);
      }
    };
    rp(options)
      .then(($) => {
        let map = {};
        let columnOne = [];
        let columnThree = [];

        $('table').find('tr td:nth-child(1)').each(function (index, element) {
          columnOne.push($(element).text());
        });

        $('table').find('tr td:nth-child(3)').each(function (index, element) {
          columnThree.push($(element).text());
        });

        columnOne.forEach((item, i) => {
          map[item] = columnThree[i];
        });

        console.log(map);
        date = map["2Late Drop Begins"];
        conv.ask("The late drop period begins on " + map["2Late Drop Begins"])
        resolve()
      })
      .catch((error) => {
        console.log(error);
        conv.ask("An error occured, please try again.");
        reject()
      })
  });

});

Надеюсь, это поможет!

...