The Beauty of ES6 Generators + co + Promises

ES6

So recently, I converted this block of code:

api.log('Running POST /history');  
var asyncJobs = [];  
var history = new api.thinky.models.History({  
    action: data.params.actionHistory,
    organization_id: data.user.organization_id
});

asyncJobs.push(function(cb) {  
    var from_record = new api.thinky.models.Record(_.merge(data.params.from_record, {
        organization_id: data.user.organization_id
    }));
    from_record.save(function(err, result) {
        history.from_record_id = result.id;
        cb(err);
    });
});

if (data.params.to_record) {  
    asyncJobs.push(function(cb) {
        var to_record = new api.thinky.models.Record(_.merge(data.params.to_record, {
            organization_id: data.user.organization_id
        }));
        to_record.save(function(err, result) {
            history.to_record_id = result.id;
            cb(err);
        });
    });
}

asyncJobs.push(function(cb) {  
    history.save(function(err, res) {
        cb(err, res);
    });
});

asyncJobs.push(function(record, cb) {  
    api.thinky.models.History.get(record.id).getJoin({ from_record: true, to_record: true }).run(function(err, res) {
        console.log(err, res);
        cb(err, res);
    });
});

async.waterfall(asyncJobs, function(err, result) {  
    data.response.result = result;
    next(err);
});

into this:

api.log('Running POST /history');  
var history = new api.thinky.models.History({  
    action: data.params.actionHistory,
    organization_id: data.user.organization_id
});
var from_record = new api.thinky.models.Record(Object.assign({}, data.params.from_record, {  
    organization_id: data.user.organization_id
}));

co(function*() {  
    var fromRecordSaveResult = yield from_record.save();
    history.from_record_id = fromRecordSaveResult.id;
    if (data.params.to_record) {
        var to_record = new api.thinky.models.Record(Object.assign({}, data.params.to_record, {
            organization_id: data.user.organization_id
        }));
        var toRecordSaveResult = yield to_record.save();
        history.to_record_id = toRecordSaveResult.id;
    }
    var historySaveResult = yield history.save();

    data.response.result = yield api.thinky.models.History.get(historySaveResult.id).getJoin({ from_record: true, to_record: true });
    next();
}).catch(next);

That's a remarkable 47 vs 23 LOC! Not to mention we get a clearer, more readable async code syntax.

ES6 generators + co library + Promises are awesome!

PS: Check out the rest of the above linked "ES6 generators" awesome tutorial.

Cheers!