al6x / synchronize

Write asynchronous code as if it's synchronous
http://alexeypetrushin.github.com/synchronize
316 stars 57 forks source link

Example use of synchronize using asynchronous promises #35

Closed davidemiceli closed 9 years ago

davidemiceli commented 9 years ago

Hi, how should synchronize work with asynchronous functions that have promises?

For example, the following case:

var sync = require('synchronize');
var knex = require('knex');

var knex = require('knex')({
    client:     "mysql",
    connection: {
      host:     "localhost",
      user:     "root",
      password: "mypassword",
      charset:  "utf8",
      database: "mydb"
    },
    pool:       {
      "min": 0,
      "max": 7
    }
 });

data = sync.await(
    //fs.readFile(fname, sync.defer())
    knex.raw('select ?', [1]).catch(function(err) {
        console.log(err);
    }).then(function(resp) {
        console.log(resp);
    });

);
console.log('Start', data);

console.log('Fine');

For example, in this case, where should I put sync.defer()? How should the code work? Could you help me?

Thanks a lot!

d3m3vilurr commented 9 years ago

defer assign to temporary variable. like this;

sync.fiber(function() {
  var defer = sync.defer();
  knex.raw(...).catch(defer).then(defer);
  var data = sync.await();
});

this is not tested. but, I think, it will work :)

al6x commented 9 years ago

Yea, it should be something like that, with supplying null as the first argument.

sync.fiber(function() {
  var defer = sync.defer();
  knex.raw(...).catch(defer).then(function(){
    arguments.unshift(null)
    defer.apply(null, arguments)
  });
  var data = sync.await();
});

It looks like a lot of code to write, but, all this should be in a helper function (it should be easy to write it), the actual code should looks like:

syncedKnex = syncWithPromises(knex)
sync.fiber(function() {
  data = syncedKnex.raw(...)
})

Where syncWithPromises is the helper function that should be written.

davidemiceli commented 9 years ago

Thanks very much, I tried also with:


var dbquery = function(query, params, fn) {

    knex.raw(query, params).catch(function(err) {
        console.log(err); return fn(null, err);
    }).then(function(resp) {
        return fn(null, resp);
    });

}
console.log('Starting...');

sync.fiber(function() {

    console.log('At first', data);
    dbquery('select 1', [], sync.defer());
    data = sync.await();
    console.log('data', data);
    console.log('Last, bye!');

});

And it works

al6x commented 9 years ago

Yep. Also, just a minor fix, it should be:

var dbquery = function(query, params, fn) {
    knex.raw(query, params).catch(fn).then(function(resp) {
        return fn(null, resp);
    });
}
davidemiceli commented 9 years ago

Yes! Thanks!!