Let's say I have a function, within which I am accessing an interface (in this case mongoose) that I can't change. The interface returns a promise that just passes in the found resource;
show = function(response) {
Resource.findById(req.params.id).then(renderResource);
}
function renderResource(resource) {
// render the response
}
In order to render the response, I need to have access to the response parameter from the show function. I can get this in using the bind function, hijacking this to be the response variable;
show = function(response) {
Resource.findById(req.params.id).then(renderResource.bind(response));
}
function renderResource(resource) {
this.send(resource);
}
But what if I want to pass another argument into the renderResource function? The only way I've managed to do it is like this;
show = function(response) {
Resource.findById(req.params.id).then(function(resource) {
renderResource.call(response, resource, "foo"));
}
}
function renderResource(resource, otherArg) {
this.send(resource);
//do something with otherArg
}
But at this point I am no longer happy with the code because;
- I have had to declare a function literal, and are well on our way to callback hell.
- I am using
callpurely so I can still usethisin the function, but actually by the time we're this far I may as well just pass inresponseas a third arg.
I am certain that there must be a pattern or something to deal with this problem in a neater way, without having to declare a new function literal. Can anyone suggest a pattern? is there a neater way of dealing with this situation?
Aucun commentaire:
Enregistrer un commentaire