简体   繁体   中英

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

Here is the code... The second .then does not work. 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.

Once the arrays are declared and res is temporarily replaced with a console.log, it appears to work on my end.

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. If that's the case, it looks like it was just a matter of declaring your arrays before pushing data to them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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