ybogdanov / node-sync

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

Returning a value from sync call #51

Closed dy closed 8 years ago

dy commented 8 years ago

Hi @ybogdanov !

I seems to not understand a simple thing: how to return a value from a function invoked in a fiber? I have almost readme example:

var Sync = require('sync');

function asyncFunction(a, b, callback) {
    process.nextTick(function(){
        callback(null, a + b);
    })
}

var result = Sync(function(){
    var result = asyncFunction.sync(null, 2, 3);

    return result;
});

console.log(result)

and this does not work. That API seemed quite obvioud for me, as far there is an intuition in the readme:

// Or simply specify callback function for Sync fiber
// handy when you use Sync in asynchronous environment
Sync(function(){

    // The result will be passed to a Sync callback
    var result = asyncFunction.sync(null, 2, 3);
    return result;

}, function(err, result){ // <-- standard callback

    if (err) console.error(err); // something went wrong

    // The result which was returned from Sync body function
    console.log(result);
})

So how it is possible to do so to return value?

I tried to write result to "outer scope" and it didn’t work. Is there a way to pass any value back from sync call at all?

Thanks.

dy commented 8 years ago

Obviously I misunderstood the sense of fibers. They are executed in separate "context", so that main thread is not blocked.

dy commented 8 years ago

deasync is what I was looking for.