Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
93 views
in Technique[技术] by (71.8m points)

javascript - i have a problem with the async functions node.js

I take information from three sites and use async functions but i don't have idea how to use then or something in response.send(arrNews) I used setTimeout(()=>response.send(arrNews), 5000) but it's not good.

app.post("/", (req, response) => {
  let arrNews = [];
  console.log("Cookies: ", req.cookies);
  const data = req.body;
  console.log(data);
  if (data.Football === "on") {
    getData({
      site: "https://www.euro-football.ru/",
      selector: ".main-news__item",
      number: data.numberNews,
    })
      .then((result) => {
        arrNews.push("Футбол");
        arrNews = arrNews.concat(result);
      })
  }
  if (data.F1 === "on")
    getData({
      site: "https://www.f1news.ru/",
      selector: ".b-news-list__title",
      number: data.numberNews,
    })
      .then((result) => {
        arrNews.push("Ф1");
        arrNews = arrNews.concat(result);
      })
  if (data.hockey === "on")
    getData({
      site: "https://allhockey.ru/",
      selector: ".summary > a",
      number: data.numberNews,
    })
      .then((result) => {
        arrNews.push("Хоккей");
        arrNews = arrNews.concat(result);
      })
  setTimeout(()=>response.send(arrNews), 5000); 
});

app.listen(3000, () => console.log("Listening on port 3000")); 
question from:https://stackoverflow.com/questions/65924919/i-have-a-problem-with-the-async-functions-node-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are basically not waiting for the function to finish before you run response.send(arrNews). You should use async/await to wait untill the function is finished. Some thing like that:

app.post("/", async (req, response) => {
  let arrNews = [];
  console.log("Cookies: ", req.cookies);
  const data = req.body;
  console.log(data);
  let myResponse;
  if (data.Football === "on") {
    const result = await getData({
      site: "https://www.euro-football.ru/",
      selector: ".main-news__item",
      number: data.numberNews,
    })
    arrNews.push("Футбол");
    arrNews = arrNews.concat(result);
  }

  if (data.F1 === "on") {
    const result = await getData({
      site: "https://www.f1news.ru/",
      selector: ".b-news-list__title",
      number: data.numberNews,
    })
    arrNews.push("Ф1");
    arrNews = arrNews.concat(result);
  }
  ........
  response.send(arrNews)
});
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...