Console.log不等待承诺

时间:2020-08-22 22:36:42

标签: javascript asynchronous web-scraping es6-promise nightmare

我对JavaScript非常陌生,试图了解异步函数的概念。因此,基本上,我使用噩梦为RateMyProfessor编写了一个webScrapper。这是功能:

var Nightmare = require("nightmare"),
  nightmare = Nightmare();
  
const baseURL =
  "https://www.ratemyprofessors.com/search.jsp?queryBy=schoolId&schoolName=University+of+California+Santa+Barbara&schoolID=1077&queryoption=TEACHER";

const getRatingProfessor = (professorName) => {
  let rating;
  let nameSplitter = professorName.split(" ");
  if (nameSplitter.length > 2) {
    professorName = nameSplitter[0] + " " + nameSplitter[1];
  }
  nightmare
    .goto(baseURL)
    .click("#ccpa-footer > .close-this")
    .type("#professor-name", professorName)
    .wait(1000)
    .evaluate(() => {
      var resultList = document.querySelectorAll("a .rating");
      //if no result is found
      if (typeof resultList === "undefined" || resultList.length == 0) {
        return "Not Found";
      }
      //Found the professor with exact name
      if (resultList.length == 1) {
        return document.querySelector("a > .rating").innerHTML;
      }
      //conficting similar professor names (rare case)
      if (resultList.length >= 2) {
        return "Cannot Determine";
      }
    })
    .end()
    .catch((err) => {
      console.log(err);
    })
    .then((text) => {
      rating = text;
      console.log(professorName, text);
    });
    return rating;
};
console.log(getRatingProfessor("XXXXX"));

如果我运行此程序,它将提供以下输出:

undefined
SomeProfName 4.8

该函数似乎在不等待诺言的情况下将等级返回到console.log。为什么函数不等待噩梦般的诺言得到解决。更重要的是,为什么评级的值没有更新?还是已经更新,但是console.log不想等待该功能?

对不起,这些问题可能看起来很荒谬,但我真的很感谢您的回答:0

1 个答案:

答案 0 :(得分:0)

您的函数明确不返回任何内容,因此默认情况下将返回undefined。您得到的是正确的,但是在then()...

之内

如果要返回异步结果,则需要将函数声明为异步,然后等待结果。

const getRatingProfessor = async (professorName) => {
  let rating;
  let nameSplitter = professorName.split(" ");
  if (nameSplitter.length > 2) {
    professorName = nameSplitter[0] + " " + nameSplitter[1];
  }
  await text = nightmare...
  return text;
};


(async () => {
   console.log(await getRatingProfessor("XXXXX"));
  }
)()