首页 > 解决方案 > 如何从 NodeJs 中的 post 函数中的函数响应?

问题描述

我有 3 个函数,每个函数都在另一个函数中,我想从最后一个函数响应。

是第一个函数(nodejs post函数):

router.post('/urls', (req, response) => {
  count = 2;
  webUrl = req.body.url;
  depth = req.body.depth;
  if (bool) {
   letstart(webUrl, count);
  }
  else {
    console.log("Finish");
  }
})

是第二个函数(请求库函数):

function letstart(urlLink, counter) {
  if (counter <= depth) {
    request(urlLink, function (error, res, body) {
      console.error('error:', error); // Print the error if one occurred
      console.log('statusCode:', res && res.statusCode); // Print the response status code if a response was received
      //console.log('body:', body); // Print the HTML for the Google homepage.
      if (!error) {
        getLinks(body);
      }
      else {
        console.log("sorry");
      }
    });
  }
  else {
    bool = false;
  }
}

这是最后一个功能:

function getLinks(body) {
  let allLists = [];
  const html = body;
  const $ = cheerio.load(html);
  const linkObjects = $('a');
  const links = [];
  linkObjects.each((index, element) => {
    var strHref = $(element).attr('href');
    var strText = $(element).text();
    var tel = strHref.startsWith("tel");
    var mail = strHref.startsWith("mailto");
    var linkInStart = strHref.startsWith("http");
    if (strText !== '' && strText !== "" && strText !== null && strHref !== '' && strHref !== "" && strHref !== null && strHref !== undefined) {
      if (!tel && !mail) {
        if (linkInStart) {
          links.push({
            text: $(element).text(), // get the text
            href: $(element).attr('href'), // get the href attribute
          });
          linkslinst.push($(element).attr('href'))
        }
        else {
          links.push({
            text: $(element).text(), // get the text
            href: webUrl.toString() + $(element).attr('href'), // get the href attribute
          });
          linkslinst.push(webUrl.toString() + $(element).attr('href'))
        }
      }
    }
  });
  const result = [];
  const map = new Map();
  count++;
  for (const item of links) {
    if (!map.has(item.href)) {
      map.set(item.href, true);    // set any value to Map
      result.push({
        text: item.text,
        href: item.href
      });
    }
  }
  resArray.push({ list: result, depth: count - 1 });
}

我只想将“resArray”响应到 react-App.js,所以我认为我首先需要将此数组返回给 post 函数。我怎样才能做到这一点?

标签: node.jspostrequest

解决方案


最简单的方法是response作为参数传递给letstart然后传递给,getLinks这样你就可以在结尾使用它getLinks,但是这个解决方案很脏,并且会使这两个函数难以重用。

更好的做法是让letstartreturn a Promise,并用body. 然后getLinks返回resArray。您将能够调用这两个函数并直接在您拥有的 post 函数中获取它们的结果response

在此处了解有关 Promise的更多信息


推荐阅读