简体   繁体   中英

Parallel calls and wait condition in NodeJS with Q or Async

I'm trying to retrieve products basis by categories, I'd like to parallel the process, first I'm not able to figure out how to write wait condition or ideal a call back method to let parent function know that all products have been retrieved from database.

I'd be open to all solution, ideally here I have used Async but want to prefer Q ( https://github.com/kriskowal/q/wiki/Examples-Gallery ) which seems to be much better choice with Mongoose and MongoDB operations.

    var temp = []
    Async.each([1,2,3,4,5,6,7,8,9...n],
        function (item, callback) {
            database.getProductsByTaxonomy(item, function (err, products) {
                temp = new Object();

                temp.TaxonomyID = item;
                temp.Products = products;

                results.push(temp);
                callback(err, products);
            });
        },
        function (err) {
            console.log(err);
        });

      <<wait for all .each call completes>>

      return temp; // or callback (err, temp); // or emit?

Any solutions?

You can use my Qx library, which simplifies working with Q and arrays:

return Qx.map(arr, function (item) {
    return getPromiseFromDb(item).then(function(products) {
        return { taxonmyId: item, products: products };
    });
});

If your DB uses callbacks rather than promises, you can use Q.ninvoke() to turn it into a promise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM