Question

How can I call a Waterline function synchronously using Sails.js. I tried

var data = Model.findOne({ foo : "bar"});

and

sync(Model, findOne);
sync.fiber(function(){
    var data = Model.findOne({ foo : "bar"});
});

None of them worked for me.

What is the right way to do that?

Was it helpful?

Solution

Waterline methods are asynchronous, plain and simple. No command will make them otherwise. You'll find this is the case for many Node methods that access external data sources (database, HTTP, etc.)

If you need to chain them in a more synchronous-feeling way, you can use a package like async to do so.

OTHER TIPS

I'm not sure this is possible for waterline. And I'm almost certain it's not the intention.

Model.findOne({ foo : "bar"}, function(err, result){
  var data = result;
});

The above would be better....don't fight the asynchronous nature of nodejs. It will only hurt later.

I'm sorry this answer is too late, you probably had found a solution by now, but for future references, here it is you may need to make the lodash global by updating /config/globals.js and set _: true then you will edit the /config/bootstrap.js with the following

global.sync = require("synchronize");
_.each(sails.models,function(model){
    _.map(model,function(attrValue,attrKey){ 
        if(typeof attrValue=="function"){
            model[attrKey+"Sync"]=sync(attrValue);
        }
    });
});

from here on you can use a synchronous version of any model function by appending "Sync" after the function like this users.findSync({fname:'Mostafa'})

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top