我是否以错误的方式使用async.js

时间:2016-04-20 12:50:16

标签: async.js

我认为我必须以糟糕的方式使用Async。我使用Async设法完成它的唯一方法是:

        var email = request.payload.email;

        async.waterfall([
            function (callback) {
                async.parallel({
                    title    : function (callbackWaterfall) {
                        async.waterfall([
                            async.apply(UserDao.findUser, email),
                            createTripTitle
                        ], callbackWaterfall)
                    },
                    tripCount: TripDao.countTrips
                }, callback)
            },
            function (results, callback) {
                TripDao.createTrip(results.title, results.tripCount, callback);
            }
        ], function (err, trip) {
            resCallback(err, request, response, trip);
        });

它删除了回调地狱,但仍然可以阅读它。

在同步代码中,我会有这个简单的代码片段:

var email = request.payload.email,
    user = UserDao.findUser(email),
    title = getTitle(user),
    tripCount = countMyTrips(),
    newTrip = TripDao.createTrip(title, tripCount);

有没有办法简化我的async.js示例?

2 个答案:

答案 0 :(得分:3)

使用async.auto

var email = request.payload.email

async.auto({
    user: async.apply(UserDao.findUser, email),
    title: ['user', function (results, callback){
        getTitle(results['user'], callback)
    }],
    tripCount: async.apply(countMyTrips),
    newTrip: ['title', tripCount', function (results, callback) {
        TripDao.createTrip(results['title'], results['tripCount'], callback);
    }]
}, function (err, results) {
    //all done
})

答案 1 :(得分:1)

由于@GolakSarangi及其async.auto解决方案,我发现async.autoInject我觉得更具可读性。

这是我的解决方案:

async.autoInject({
            tripCount: TripDao.countTrips,
            email: function(callback){ callback(null /*err*/, request.payload.email) },
            user: ['email', UserDao.findUser],
            title: ['user', createTripTitle],
            trip: ['title', 'tripCount', TripDao.createTrip]
        }, ['trip', function(err, trip){
            resCallback(err, request, response, trip);
        }]);