node.js - 如何从 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 函数。我怎样才能做到这一点?
解决方案
最简单的方法是response
作为参数传递给letstart
然后传递给,getLinks
这样你就可以在结尾使用它getLinks
,但是这个解决方案很脏,并且会使这两个函数难以重用。
更好的做法是让letstart
return a Promise
,并用body
. 然后getLinks
返回resArray
。您将能够调用这两个函数并直接在您拥有的 post 函数中获取它们的结果response
。
在此处了解有关 Promise的更多信息
推荐阅读
- ruby-on-rails-6 - Rails 生产容器“您要查找的页面不存在。”
- http-status-codes - “Too Soon to Renew JWT Token”的适当 HTTP 状态代码
- excel - 从 Excel 读取时,Pandas 将整数转换为实数
- google-api - 从 Nest-camera 获取单个图像
- javascript - 如何创建具有创建和加入大厅功能的网站
- javascript - 我正在尝试用 Javascript 编写一个基本的国际象棋引擎。该板是一个数组数组。为什么我不能让棋子移动?
- python - 为什么我不能将我的游戏的画布与“锚”或“对齐”对齐?他们都抛出一个错误
- python - 我的 webscraper 陷入了一个循环
- c++ - msgpack c++ 无法写入管道
- google-cloud-platform - 弃用 GCP 旧式元数据端点 - 如何测试我是否不再使用它们?