簡體   English   中英

為什么諾言鏈接在Node.js中不起作用?

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

我有一個腳本可以抓取一個網站,並且應該將數據發送回客戶端...只需您就知道app.get中的全部內容

這是代碼...第二個.then不起作用。 一旦遍歷數組,應該將數組填充到客戶端之后再發送給客戶端。 但這不起作用...我設定第二個承諾的方式可能有問題嗎? 請幫忙。

  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});
         })

在提供的代碼段中,沒有聲明任何數組,並且沒有res對象調用“ send”,因為沒有任何對象傳遞到函數中。

一旦聲明了數組並將res臨時替換為console.log,它似乎可以正常工作。

工作代表

我假設您在路由中調用了此函數,因此在此函數的范圍內應該有一個“ res”對象可用。 如果是這種情況,則看起來只是在將數據推送到數組之前聲明了數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM