2016-06-28 100 views
0

我正在调用一个在查询数据库后返回对象的函数。但我很努力地让函数等待数据库返回结果,然后再返回最终的数据。等待Rethinkdb答应在返回父函数之前返回结果

请有人建议如何等待数据库查询完成?

addBasket: function(prodId, cookie) { 
    var nextCookie = cookie; 
    db.table('Events').filter({id: prodId}).pluck('eventName').run().then(function(result){ 
     newData.prodName = result[0].eventName; 
     nextCookie.basket.push(newData); 
     return nextCookie; 
    }).error(function(err){ 
     return; 
    }) 
} 
+1

你会想'return'从'addBasket'承诺这样你就可以等待它。 – Bergi

回答

0

你会希望addBasket返回一个承诺

var funcs = { 
    addBasket: function(prodId, cookie) { 
     var nextCookie = cookie; 
     return new Promise(function(resolve, reject){ 
     db.table('Events').filter({id: prodId}).pluck('eventName').run().then(function(result){ 
      newData.prodName = result[0].eventName; 
      nextCookie.basket.push(newData); 
      resolve(nextCookie); 
     }).error(reject) 
     }); 
    } 
} 

那么你可以做

funcs.addBasket(..args).then(function(nextCookie){....})