在单个快速路由呼叫中调用多个功能?

时间:2020-07-13 22:13:09

标签: javascript node.js express asynchronous cheerio

我用cheerio.js创建了一个Web抓取功能,当用户打开主页时,我想调用它。我使用了一个功能,但是实际上我有3个抓取功能,它们的功能都稍有不同。如何将这些函数与第一个函数调用一起添加到我的主页路由调用中? (基本上,我希望在用户打开主页时将所有数据抓取)

我对async / await或promises也不太熟悉,并通过在线以下示例使此代码正常工作,因此如果出现问题,请告诉我!

表示有效的路由呼叫(index.js):

const getSUPResults = require("./routes/SUPstores");
app.use(getSUPResults);

app.get("/", async function(req, res, next){
  const result = await getSUPResults();
  res.render("index", result);
});

抓取功能("./routes/SUPstores"

const express = require("express");
const cheerio = require("cheerio");
const { default: Axios } = require("axios");

const fetchData = async () => {
    const result = await Axios.get("http://example.com");
    return cheerio.load(result.data);
};

const getSUPResults = async () => {
    const $ = await fetchData();
    const SUPStoreInfo = [];

        $('.row > tbody > tr:contains("SUP")').each(function(i, element){
            const SUPResult = {
                "environment" : $(this).children().text(),
                "store" : $(this).children().next().text(),
                "version" : $(this).children().next().next().text()
            };
            SUPStoreInfo.push(SUPResult);
        });
        return SUPStoreInfo;
}

module.exports = getSUPResults;

我试图做这样的事情,但是它似乎只调用了第一个函数(getSUPResults),而忽略了其余的。有什么可以尝试的类似方法吗?

const getSUPResults = require("./routes/SUPstores");
const getQAResults = require("./routes/QAstores");
const getDEVResults = require("./routesDEVstores");

app.use(getSUPResults);
app.use(getQAResults);
app.use(getDEVResults);

app.get("/", async function(req, res, next){
  const SUP = await getSUPResults();
  const QA = await getQAResults();
  const DEV = await getDEVResults();
  const result = [SUP, QA, DEV];
  res.render("index", result);
});

0 个答案:

没有答案