【发布时间】:2019-01-26 00:12:44
【问题描述】:
我正在处理一个异步问题。我正在制作一个网络抓取工具,在抓取网络之后,我需要将数据放入我的 MongoDB 数据库中。我需要将它发送到前端,但是由于我有一个循环元素,所以我不能把res.json()放进去,会报错(res.json())之后只能发送一次。
我被困在这里了。我以前使用过 promise,但这很令人困惑。
router.get('/scrape', (req, res) => {
request('http://www.nytimes.com', function test(error, response, html) {
const $ = cheerio.load(html);
// An empty array to save the data that we'll scrape
const results = [];
$('h2.story-heading, p.summary').each(function(i, element) {
const link = $(element)
.children()
.attr('href');
const title = $(element)
.children()
.text();
const summary = $(element)
.children()
.text();
const data = {
title: title,
link: link,
summary: summary,
};
articles
.create(data)
.then((resp) => results.push(resp))
// .then((resp) => Promise.resolve(results)) //
// .then((jsonDta ) => res.json(jsonData)) // error you can only give response once.
.catch((err) => reject(err));
});
console.log(results); // empty array
res.json(results)// empty
});
});
我的计划是:
- 抓取网站(循环元素)
- 然后保存到 MongoDB(将数据推送到数组中)
- 然后在循环之后将其传递给前端。
我需要将查询方法create... 放在循环中,因为我需要每个数据都有一个id。
【问题讨论】:
-
在这种情况下我应该把我的承诺放在哪里?那是我的问题。
标签: node.js asynchronous promise es6-promise scrape