deasync: deasync hangs in an asynchronous context

When using a deasynced function in asynchronous code, deasync hangs and never returns.

var deasync = require('deasync');

function async(cb) {
  setTimeout(function() {
    cb(null, 'value');
  }, 0);
}

function sync() {
  return deasync(async)();
}

console.log('start', sync());
async(function(err, val) {
  console.log('async result', val);
  console.log(sync());
  console.log('done');
});

Notice that when run, the second call to sync hangs. I was originally using promises when testing this and derived the previous code from this:

var Promise = require('q');
var deasync = require('deasync');

function async() {
  return Promise.resolve('value');
}

function sync() {
  var result, done;
  async().then(function(response) {
    result = response;
  }).finally(function() {
    done = true;
  });

  deasync.loopWhile(function() { return !done; });

  return result;
}

console.log('start', sync());
async().then(function(result) {
  console.log('async result', result);
  return sync();
}).then(function(value) {
  console.log(value);
  console.log('done');
});

I also tried the above example using the Bluebird promise library and ended up with the same results. In the promise example, adding a console.log inside the loopWhile handler shows that it is stuck checking done since the promise chain never completes.

About this issue

  • Original URL
  • State: open
  • Created 9 years ago
  • Reactions: 8
  • Comments: 18 (3 by maintainers)

Commits related to this issue

Most upvoted comments

I’d say this package isn’t really necessary more, now that async functions exist.

On Thu, Jan 24, 2019, 7:31 AM Jam Risser notifications@github.com wrote:

Is there any way to work around this bug?

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/abbr/deasync/issues/21#issuecomment-457180359, or mute the thread https://github.com/notifications/unsubscribe-auth/AH996cZP3D8NQJAhCQK0wR_E4gyPdNIsks5vGaeLgaJpZM4FT0W0 .

Wrapping the code into process.nextTick somehow helped me though, I don’t know if this is related

@codejamninja

Is there any way to work around this bug?

i was able to get around this by not using deasync and hiding my asyncronous code behind the syncronous require call - i put the needed information (from the async function call) on the global context. there’s probably a better way, but that’s how i did it

Much more simple example:

var deasync = require('deasync');

function async(cb) {
    console.log('1');
    setTimeout(function() {
        console.log('2');
        cb(null, 'value');
        console.log('3');
    }, 0);
}

console.log('A', deasync(async)());
setTimeout(function() {
    console.log('B', deasync(async)());
}, 0);

I had:

$ node test.js 
1
2
3
A value
1
^C