Anonymous Anonymous - 6 months ago
793 0

No description

Javascript

promises vs async

exports.index = function(req, res) {

    // PROMISES
    function book_count() {
        return new Promise((resolve, reject) => {
            Book.count().then(function(count) {
                resolve({book_count : count});
            }, function(err) {
                reject(err);
            })
        });
    };

    function book_instance_count() {
        return new Promise((resolve, reject) => {
            BookInstance.count().then(function(count) {
                resolve({book_instance_count : count});
            }, function(err) {
                reject(err);
            })
        });
    };

    function book_instance_available_count() {
        return new Promise((resolve, reject) => {
            BookInstance.count({status:'Available'}).then(function(count) {
                resolve({book_instance_available_count : count});
            }, function(err) {
                reject(err);
            })
        });
    };

    function author_count() {
        return new Promise((resolve, reject) => {
            Author.count().then(function(count) {
                resolve({author_count : count});
            }, function(err) {
                reject(err);
            })
        });
    };

    function genre_count() {
        return new Promise((resolve, reject) => {
            Genre.count().then(function(count) {
                resolve({genre_count : count});
            }, function(err) {
                reject(err);
            })
        });
    };
    
      
    let promises = [book_count(), book_instance_count(), book_instance_available_count(), author_count(), genre_count()];

    Promise.all(promises)
        .then(values => { 
            let results = Object.assign({}, ...values);
            res.render('index', { title: 'Local Library Home', error: null, data: results });
        }, reason => {
            console.log(reason)
    });

    // VS

    // ASYNC
    async.parallel({
        book_count: function(callback) {
            Book.count(callback);
        },
        book_instance_count: function(callback) {
            BookInstance.count(callback);
        },
        book_instance_available_count: function(callback) {
            BookInstance.count({status:'Available'},callback);
        },
        author_count: function(callback) {
            Author.count(callback);
        },
        genre_count: function(callback) {
            Genre.count(callback);
        },
    }, function(err, results) {
        console.log(results);
        res.render('index', { title: 'Local Library Home', error: err, data: results });
    });
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download