如何在节点js中同步我的函数调用?

这是我的routes.js

app.route('/api/book/:id') .get(function(req,res){ var id=req.params.id; bookapi.getBookDetails(id,res); }); 

这是它所调用的function

 scope.getBookDetails=function(bookId,res){ console.log('unnecessary thing@@'); //var bookId=req.params.id; connection.query({ sql:"SELECT name,description FROM books WHERE books.id=?", values:[bookId] }, function (err,results) { if(err) throw err; if(results.length>0){ var x=scope.getGenre(bookId); console.log(x +"hello"); res.send(JSON.stringify(results)+scope.getAuthors(bookId)+scope.getGenre(bookId)); } } ) } 

我也使用angular度,所以当一个get请求被发送到'/ books /:bookId'它调用这个控制器:

function($范围,$ routeParams,$ HTTP){

 $http.get('/api/book/'+$routeParams.bookId).success(function(bookdetails){ $scope.bookdetails=bookdetails; }) } 

这是我的服务器端控制台:

 unnecessary thing@@ undefinedhello GET /api/book/1 304 16.577 ms - - 

在我的客户端控制台,我得到的答复

 [{"name":"The Alchemist","description":""}]undefinedundefined 

在我的服务器端控制台getBookDetails被调用之前id = 1甚至可以通过“/ api / book / 1”。 为什么发生这种情况? 为什么不同步? 我应该学习这个asynchronous吗?

谢谢

req.params.id分配给一个variablesid总是同步的,所以问题不在那里。 问题可能是getGenregetAuthors是asynchronous的,所以必须将依赖于结果的任何东西移动到callback函数中。

一个更简单的方法是使用承诺。 学习JavaScript诺言库很有趣,是bluebird 。 它应该让事情变得更容易。

 app.route('/api/book/:id') .get(function(req,res){ var id=req.params.id; bookapi.getBookDetails(id).then(function(result){ res.send(result) }); }); scope.getBookDetails=function(bookId){ console.log('unnecessary thing@@'); //var bookId=req.params.id; return Promise.promisify(connection.query)({ sql:"SELECT name,description FROM books WHERE books.id=?", values:[bookId] }) .then(function (results) { if(results.length>0){ return Promise.props({ // getGernre should return a promise just like this function. // if it accepts a callback, you can do // Promise.promisify(scope.getGenre) and use that instead genre: scope.getGenre(bookId), authors: scope.getAuthors(bookId), results: results, }) } }) .then(function (dict){ if(dict){ console.log(dict.genre +"hello"); return JSON.stringify(dict.results)+dict.authors+dict.genre; } }) }