2017-04-05 70 views
0

我目前正在使用外部API構建Web服務並使用Cheerio來抓取數據。我能夠從Cheerio獲取數據並嘗試將新變量從抓取中移動到項目數據(文章)。我試過item.push({「新內容」:這裏有新內容)),以及返回(變量名稱),但我無法將新變量追加到字段image_url。我不喜歡Cheerio和整體服務的輸出。NodeJS:無法將新數據推送到陣列

如何去附加內容變量?

request("<API URL HERE>", function(error, response, body) { 
var myObject = JSON.parse(body); 
var listing = myObject.items; 

arr = listing.map(function(item) { 

    var url = item.url; 
    //get individual images for articles based on URL 
    update = request(url, function (error, response, body) { 
     if (!error) { 
     var $ = cheerio.load(body) 
     content = $('.post-body').find('img').attr('src'); 
     return content; 

     } 
     else { 
     console.log("We’ve encountered an error: " + error); 
     } 
    }); 

    //return format for each article 
    return { 
     "title": item.title, 
     "subtitle": item.content.substr(0,100), 
     "image_url": update.content, 
     "buttons": 
      [{ 
       "type":"web_url", 
       "url":item.url, 
       "title":"View Item" 
      }] 

    }; 
}); 

res.send({ 
    "messages": [ 
    { 
    "attachment":{ 
    "type":"template", 
    "payload":{ 
     "template_type":"generic", 
     "elements": arr 
     } 
    } 
    } 
] 
}) 
}); 
+0

做推內'request'因爲你是從一些外部源請求數據和這些數據將在未來一段時間內提供。 –

+0

由於您正在處理異步事件,因此當您執行「push」時,數據尚未到達。您應該使用[Promise](https://developers.google.com/web/fundamentals/getting-started/primers/promises) – Tolen

回答

0

在處理外部API數據庫等時,代碼變得異步。這意味着,當您發送更新請求時,變量內容將不確定,因爲響應尚未返回。 Node提供了很多方法來處理異步代碼。一個很酷的方式是承諾。如果你不知道的承諾,只是閱讀:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

你應該做的是這樣的:

var url = item.url; 
    //get individual images for articles based on URL 
    const update =() => { 
    return new Promise((resolve,reject) => { 
    request(url, function (error, response, body) { 
    if (!error) { 
     var $ = cheerio.load(body) 
     content = $('.post-body').find('img').attr('src'); 
     resolve(content); 

    } 
    else { 
     reject(error) 
    } 
    }); 
} 
}) 
相關問題