ybogdanov / node-sync

Write simple and readable synchronous code in nodejs using fibers
MIT License
492 stars 70 forks source link

A small minor modification to remove context on `.sync()` #35

Closed bugs181 closed 10 years ago

bugs181 commented 10 years ago

I was having a problem adapting old projects where I wanted a custom Function.prototype that could switch between normal callback style and .sync() style.

For that reason I made a small minor modification that allows you to do something like:

var Sync = require('sync');

Sync(function() {
    var result = do_something_useful.sync("param 1", "some other param");
});

Rather than do_something_useful.sync(null, "param 1", "some other param");

The modification is to remove the arguments loop, and ignore the context object inside the .sync() function.

// Prepare args (remove first arg and add callback to the end)
// The cycle is used because of slow v8 arguments materialization
/*for (var i = 1, args = [], l = arguments.length; i < l; i++) {
    args.push(arguments[i]);
}*/

var args = Array.prototype.slice.call(arguments, 0);
args.push(syncCallback);

// call async function
this.apply(null, args);

I'm only sharing this because I thought it might help somebody else. Cheers.

NOTE: You WILL lose the ability to have a context. I.E. You can no longer use this or a reference to any other object for .sync(). Please understand this before making the modification.

bugs181 commented 10 years ago

Update: Went ahead and added a setContext method for those pesky modules that needed it. ;)

Function.prototype.setContext = function(obj) {
    this.__context = obj;
}

Inside Function.prototype.sync = function(obj /* arguments */)

    // call async function
    if (this.__context) { 
        this.apply(this.__context, args);
    } else {
        this.apply(null, args);
    }

Example:

var Sync = require('sync');

Sync(function() {
    do_something_useful.setContext( this );
    var result = do_something_useful.sync("param 1", "some other param");
});