【发布时间】:2019-01-20 12:13:42
【问题描述】:
我是 Node.Js 的新手。 我想在另一个函数中进行函数调用,当一切都完成后,打印一个文件。
但是函数是异步的,所以当第一个结束节点打印文件而不等待第二个..
我尝试了异步库的瀑布方法,但不是我需要的瀑布.. Async 是一个有很多不同模式的大型库,也许其中之一就是解决方案
这是代码:
request(url, function (error, response, html) {
var json_list = [];
if (!error) {
var $ = cheerio.load(html);
$('.fixed-recipe-card').each(function () {
var json = {title: "", description: "", rating: "", ingredients: [], url: ""};
json.title = $(this).children().last().children().first().text().trim();
json.description = $(this).children().last().children().first().next().children().last().text().trim();
json.rating = $(this).children().last().children().first().next().children().first().children().first().attr('data-ratingstars');
json.url = $(this).children().last().children().first().next().attr('href');
request(json.url, function (error, response, html) {
var $ = cheerio.load(html);
$('.checkList__line').filter(function () {
var ingredient = $(this).children().first().children().last().text().trim();
if (ingredient !== "Add all ingredients to list") {
console.log(ingredient);
json.ingredients.push(ingredient);
}
});
});
json_list.push(json);
});
}
fs.writeFile('output.json', JSON.stringify(json_list, null, 4), function (err) {
console.log('success');
})
res.send(JSON.stringify(json_list));
});
【问题讨论】:
-
检查我的更新答案
-
它有效!谢谢!
标签: node.js asynchronous async.js cheerio