简体   繁体   English

为什么诺言链接在Node.js中不起作用?

[英]Why does promise chaining not work here in Node.js?

I have a script that scrapes a website and is supposed to send data back to client... JUST SO YOU KNOW IT'S ALL WITHIN app.get 我有一个脚本可以抓取一个网站,并且应该将数据发送回客户端...只需您就知道app.get中的全部内容

Here is the code... The second .then does not work. 这是代码...第二个.then不起作用。 It's supposed to send the arrays to the client after they have been populated once cheerio iterated through them. 一旦遍历数组,应该将数组填充到客户端之后再发送给客户端。 Yet it does not work... Maybe something wrong with the way I set up the second promise? 但这不起作用...我设定第二个承诺的方式可能有问题吗? Please help. 请帮忙。

  axios.get("https://www.sciencenews.org/").then(function(response){
     var $ = cheerio.load(response.data);
     $("div.field-item-node-ref").each(function(i,element){
       if($(element).children('.ad').length == 0 && $(element).children('article').length > 0) {
                    array1.push($(element).find('h2.node-title').text());
                    array2.push($(element).find('div.content').text());
 array3.push(`https://www.sciencenews.org${$(element).find('a').attr('href')}`);
                    array4.push(`${$(element).find('img').attr('src')}`);
                 }
            })
        }).then(()=>{
            res.send({titles:array1,summaries:array2,links:array3,base64img:array4});
         })

In the provided code snippet, none of the arrays are declared and there is no res object to call 'send' on since none is passed into the function. 在提供的代码段中,没有声明任何数组,并且没有res对象调用“ send”,因为没有任何对象传递到函数中。

Once the arrays are declared and res is temporarily replaced with a console.log, it appears to work on my end. 一旦声明了数组并将res临时替换为console.log,它似乎可以正常工作。

Working Repl.it 工作代表

I'm assuming on your end that this function is called within a route, so there should be a 'res' object available within the scope of this function. 我假设您在路由中调用了此函数,因此在此函数的范围内应该有一个“ res”对象可用。 If that's the case, it looks like it was just a matter of declaring your arrays before pushing data to them. 如果是这种情况,则看起来只是在将数据推送到数组之前声明了数组。

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

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