[英]Why cant I pull the callback out of the app.get function in node and express.js?
I'm trying to do this in my server.js file: 我正在尝试在我的server.js文件中执行此操作:
// doesn't work... don't know why.
var findBooks = function (err, books) {
if (!err) {
return response.send(books);
} else {
console.log(err);
}
}
// Get all books
app.get('/api/books', function (request, response, err, books) {
return BookModel.find( findBooks(err, books));
});
and it gives me a 404 error when I run a jQuery xhr in the console, and the same error when I request the page in the browser. 当我在控制台中运行jQuery xhr时,它给我一个404错误,而当我在浏览器中请求页面时,它给了同样的错误。 It works if I put the callback in the usual place, moving the findBooks
function into the BookModel.find
function where it's called and deleting the last two arguments of app.get
. 如果我将回调放置在通常的位置,将findBooks
函数移动到调用它的BookModel.find
函数中,然后删除app.get
的最后两个参数,则app.get
。 I'm working though Chapter 5 of Addy Osmani's Backbone.js Applications book to give you some context. 我正在研究Addy Osmani的Backbone.js应用程序一书的第5章,为您提供一些背景信息。 Why doesn't this work? 为什么不起作用? Is doing this a good thing, or am I trying something that isn't recommended? 这是一件好事,还是我尝试了不推荐的事情?
You have two problems: 您有两个问题:
findBooks
tries to access response
, but response
is not in scope at that point. findBooks
尝试访问response
,但是此时response
不在范围内。 findBooks
with err
and books
and passing the return value to BookModel.find
, when you probably want to pass the function for find
to call. 当您可能希望将函数传递给find
进行调用时,您将使用err
和books
调用findBooks
并将返回值传递给BookModel.find
。 Let's first solve the second problem. 让我们首先解决第二个问题。 Rather than calling the function, just pass it: 而不是调用该函数,只需传递它:
return BookModel.find(findBooks);
That was easy. 那很简单。 Now, to solve the first problem, we'll need to add an extra argument to findBooks
. 现在,要解决第一个问题,我们需要在findBooks
添加一个额外的参数。 I'll assume you put it at the start for reasons I'll detail later. 我会假设您将其放在开头,因为稍后会详细说明。 Then we can change the usage to look like this: 然后,我们可以将用法更改为如下所示:
return BookModel.find(function (err, books) {
return findBooks(response, err, books);
});
It turns out, though, that there's a more concise way to do that, using bind
. 但是事实证明,使用bind
可以实现一种更简洁的方法。 bind
is best known for its use in binding the value of this
, but it can also be used to bind arguments: bind
以绑定this
的值而闻名,但是它也可以用来绑定参数:
return BookModel.find(findBooks.bind(null, response));
All together, we get: 总之,我们得到:
function findBooks (response, err, books) {
if (!err) {
return response.send(books);
} else {
console.log(err);
}
}
// Get all books
app.get('/api/books', function (request, response) {
return BookModel.find( findBooks.bind(null, response) );
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.