【问题标题】:Async function called in a async function Node.Js在异步函数 Node.Js 中调用的异步函数
【发布时间】: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


【解决方案1】:

你可以使用 Promises:

let promises = [];

$('.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');

    let p = new Promise(function(resolve, reject) {
        request(json.url, function (error, response, html) {
            if(error) { reject(error); } // reject promise on error

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

            resolve(response); // promise success
        });
    });
    promises.push(p);

});

Promise.all(promises).then(function(values) {
    console.log(values);
    fs.writeFile('output.json', JSON.stringify(json_list, null, 4), function (err) {
        console.log('success');
    })
    ...
});
...

使用 Promise.all,您可以在所有异步调用(构建为 Promise)都已解决时执行某些操作

查看此链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2015-01-22
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 2020-03-09
    • 2019-07-04
    • 1970-01-01
    相关资源
    最近更新 更多