2015-12-15 68 views
2

這裏是我的routes.js如何在節點js中同步我的函數調用?

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

,這裏是它

scope.getBookDetails=function(bookId,res){ 
    console.log('unnecessary [email protected]@'); 
    //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)); 
     } 
    } 
    ) 
} 

我使用的角度也因此,當一個GET請求發送到調用函數「/書/:BOOKID」調用該控制器:

函數($範圍,$ routeParams,$ HTTP){

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

這是我的服務器端的控制檯:

unnecessary [email protected]@ 
undefinedhello 
GET /api/book/1 304 16.577 ms - - 

在我的客戶端控制檯我得到的迴應

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

在我的服務器端控制檯getBookDetails被ID = 1甚至可以通過調用之前通過'/ api/book/1'。這是爲什麼發生?爲什麼它不同步?我應該學習異步嗎?

謝謝

回答

0

分配req.params.id一個變量id始終是同步的,所以這個問題是不存在的。問題可能是因爲getGenregetAuthors是異步的,所以必須將依賴於結果的任何內容移動到回調函數中。

一個簡單的方法是使用承諾。學習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 [email protected]@'); 
    //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; 
     } 
    }) 
} 
+0

謝謝你的時間。承諾似乎是一個可行的解決方案。但是,我仍然不明白爲什麼getBookDetails函數在GET/api/book/1請求被髮送之前被調用。 – She

+0

它沒有,你可以在getBookDetails的開頭寫'console.log(bookId)',它應該打印1 – MIE

+0

這讓我發瘋,有時間回頭去學習,從一開始就學習東西。使用回調會導致功能太多。使用承諾意味着我必須再次學習新的東西。 – She