#245·co

co.defer feature request

Author: rumkinCreated Oct 2, 2015Updated Mar 18, 2020

What's about golang-like deferred calls with co? I think it should looks like that:

javascript
co(function *(){
    var db = yield DB.connect();
    // Add deferred function
    yield co.defer(function(){
        db.close();
    }); 

    var doc = db.collection('collection').findById(1);

    if (! doc) {
        throw new Error('Document not found');
    }

    doc.counter += 1;

    yield doc.save();
});

In this way db connection will be closed in any way after throwing or returning. Yielding of methods wrapped in defer should return control immediately and put deferred call into deferred stack.