Search code examples
node.jssynchronize

2nd step never gets called inside fiber (synchronize.js)


I'm trying to work with synchronize.js to run some functions that must be executed synchronously. I've read something about it here and here.

To try it out, I've created the following code

var sync = require('synchronize');
var fiber = sync.fiber;
var await = sync.await;
var defer = sync.defer;

function function1(){
    console.log("Executing function 1")
}

sync.fiber(function() { 
console.log('Before');
var step1 = await(setTimeout(function1, 1000, defer()));
var step2 = console.log('After');
}); 

console.log('Outside');

Logic tells me the output should be

Before
Outside
Executing function 1
After

But what I get is

Before
Outside
Executing function 1

Somehow, step2 is not being executed and I can't figure out why.


Solution

  • I've never used this plugin before but try this:

    var sync = require('synchronize');
    var fiber = sync.fiber;
    var await = sync.await;
    var defer = sync.defer;
    
    function function1(callback){
        // defer expects this to be asynchronous (so it needs to execute a callback)
        console.log("Executing function 1")
        callback();
    }
    
    sync.fiber(function() { 
    console.log('Before');
    var step1 = await(setTimeout(function1, 1000, defer()));
    var step2 = console.log('After');
    }); 
    
    console.log('Outside');
    

    Basically I think calling defer prematurely (before the callback is executed) causes it to hang.

    Edit:

    After reading the documentation I now realize that defer creates a callback function. That would mean it's hanging because the callback it creates is never called. Let me know if this works.