简体   繁体   English

NodeJS - 运行函数以加载变量

[英]NodeJS - running function to load in variables

I was wondering how I would go about making this function ( scrapData ) only run once, so that it doesn't increment each item and loads in all at once.我想知道如何让这个函数 ( scrapData ) 只运行一次,这样它就不会增加每个项目并一次加载。 Here's an image of what's happening in my CMD.这是我的 CMD 中发生的事情的图像。 I'm not very familiar with JS so I'm not really sure what I'm doing wrong.我对 JS 不是很熟悉,所以我不确定我做错了什么。 在此处输入图片说明

And here is a snippet of code for that one command:这是该命令的一段代码:

//latest articles command
if (message.content.startsWith(prefix + 'latest')) {

    //website url variables
    const website_domain = "https://hypebeast.com/";
    let website_path = args[0];
    let website_url = website_domain + website_path;

    //extra arguments variable
    let extra_arg = args.slice(1).join(" ");

    //if user inputs too many arguments
    if (extra_arg.length > 0) {
        message.reply('too many arguments! Please refer to `h.help` for correct usage.');

    } else {
        
        //opening url and loading in websites html
        function scrapData(website_url) {
            return rp(website_url)
                .then(body => {
                    var items = [],
                        $ = cheerio.load(body);
                    
                    //web scraping here
                    $('.post-box').each(function() {
                        var title = $(this).find($('.title h2 span')).first().text(),
                            caption = $(this).find($('.post-box-excerpt p')).first().text(),
                            article_url = $(this).find($('.col-hb-post-image a')).first().attr('href'),
                            thumbnail_long = $(this).find($('.thumbnail img')).first().attr('src');
                        
                        //adding title, caption, etc to list
                        items.push({title, caption, article_url, thumbnail_long});

                        //check items in console
                        console.log(items);
                    })
                    return items;
                })
        }

        //run webscraping function
        scrapData(website_url)
            .then(items => {
                //produce embed messages
                for (i = 0; i < items.length; i++) {
                    message.channel.send({
                        embed: {
                            color: config.embed_colour,
                            title: (i + 1 + ". " + items[i].title),
                            url: items[i].article_url,
                            description: items[i].caption,
                        }
                    })
                }
                message.channel.send("`SOURCE: " + website_url + "`");
                console.log('DONE!');
            })    
    }
    }

Actually, your function is only running once already.其实,你的函数运行一次了。 scrapData is only called once from code not in a loop or each statement (I assume the top of the code snippet is the beginning of the command). scrapData只从不在循环中的代码或each语句中调用一次(我假设代码片段的顶部是命令的开头)。 To decrease the amount of console messages logged consider moving the console.log call to the line right above the return statement.要减少记录的控制台消息数量,请考虑将console.log调用移动到return语句正上方的行。

As a direct response to your comment it only requests info from the website once, when you call rp(url) .作为对您评论的直接回复,当您致电rp(url)时,它只会从网站请求信息一次。 The then body attached to that contains a loop that acts on the return from rp , but it has already completed its work (that's what the Promise guarantees: execute this after something else finishes).附加到它的then主体包含一个循环,该循环作用于rp的返回,但它已经完成了它的工作(这是 Promise 保证的:其他事情完成执行它)。 cheerio works completely offline and any data it works with is already fully downloaded at the time of execution, the name of the function it uses ( load ) is simply somewhat misleading in the context of your program. cheerio完全离线工作,并且它处理的任何数据在执行时已经完全下载,它使用的函数名称( load )在您的程序上下文中只是有点误导。 rp gets the body, cheerio is simply parsing it. rp得到身体, cheerio只是解析它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM