在异步函数Node.Js中调用的异步函数

时间:2018-08-13 17:42:36

标签: node.js asynchronous async.js cheerio

我是Node.Js的新手。 我想在另一个函数中进行函数调用,当一切完成后,打印文件。

但是这些函数是异步的,因此当第一个结束节点打印文件时,无需等待第二个结束。

我尝试了Async库的Waterfall方法,但不是我需要的Waterfall .. 异步是一个大型库,具有许多不同的模式,也许其中一个是解决方案

这是代码:

@Override
public void onBackPressed() {
    // Do your exit task here
}

1 个答案:

答案 0 :(得分: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。在解决了所有异步调用(按承诺构建)后,您可以执行某些操作

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

希望这会有所帮助