等待Rethinkdb promise在返回父函数之前返回结果

时间:2016-06-28 20:26:53

标签: javascript node.js 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 个答案:

答案 0 :(得分: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){....})