问题
I am using Sails' ORM (Waterline). I have written a geturl
service that should return the url of several models/actions in my app. I am currently calling this service inside my templates.
(As I am alone to develop this, don't hesitate to warn me if this design pattern is wrong)
Now it occurs that Waterline's .find()
method is asynchronous (as it should). I always use callbacks to do things when inserting or fetching things in database.
Now I have seen everywhere that I cannot return any data from asynchronous methods. As a consequence I am puzzled because I want to create this [damned] service to centralize the URL management.
Here is my current code:
module.exports = {
variete: function(id_objet) {
var string = '/default_url';
return onvariete(id_objet, function (err, url) {
if (err) {
sails.log.error('Error : ', err);
} else {
return url;
}
});
}
};
function onvariete(id_objet, next) {
var url = '/';
return Variete.findOne({id:id_objet}).exec(function (err, v) {
sails.log.info('URL Variety : '+ v.nom + ' / ' +id_objet + ' / ' + v.slug);
if (err) {
sails.log.error('Error : ' + v.nom + ' / ' + err);
// Do nothing.
return next(new Error('Variete error'), undefined);
} else if (!v) {
return next(new Error('Variete not found'), undefined);
} else if (!v.slug) {
// variete doesn't have a slug field
// we redirect to /v/:id
url += 'v/' + v.id;
return next (null, url);
} else {
// Ok variete has got a slug field
sails.log.info('GOT A SLUG! ' + v.slug);
url += 'variete/' + v.slug;
return next (null, url);
}
});
}
I made a static
object that embeds my geturl
service, and then inside a Jade template:
a(href="#{s.geturl.variete(ann.variete.id)}" title="#{ann.variete.name}") #{ann.variete.name}
And I can get something like:
<a title="Tomate Coeur de Boeuf" href="undefined">Tomate Coeur de Boeuf</a>
Thank you by advance.
回答1:
The solution vas to write a .url(bool)
instance method. See how to write instance methods in Sails / Waterline.
This way I directly access this method from my template : a(href="#{ann.variete.url()}" title="#{ann.variete.name}") #{ann.variete.name}
.
Done!
来源:https://stackoverflow.com/questions/26463552/service-that-returns-data-from-an-asynchronous-method