2015-08-17 38 views
-1

在更新最高價格的循環完成之前,來自Product.find()的承諾正在解決。只有在數據操作完成後,我如何才能解決承諾?這個承諾爲什麼早日解決?

Product.find({'prodType': req.params.type}).lean().exec(function (err, product) { 

    if (err) { 
     res.status(400); 
    } 

    for (var i = 0; i < product.length; i++) { 

     (function(u) { 

      Option.find({'prodId': product[i].productId}).lean().sort({price: -1}).limit(1).exec(function (err, highest) { 

       product[u].price = highest; 
       // not updated in returned object 

      }); 

     })(i); 

    } 

}).then(function (product) { 

    res.send(product); 

}); 

回答

0

全部移動從.exec()回調到.then的代碼,並返回一個新的承諾,就當所有的其他承諾完成解析。

Product.find({'prodType': req.params.type}).lean().exec() 
.then(function (product) { 
    var promises = []; 
    for (var i = 0; i < product.length; i++) { 

     (function(u) { 

      promises.push(Option.find({'prodId': product[i].productId}).lean().sort({price: -1}).limit(1).exec(function (err, highest) { 

       product[u].price = highest; 
       // not updated in returned object 

      })); 

     })(i); 

    } 
    return Promise.all(promises).then(function() { 
     // we want to pass the original product array to the next .then 
     return product; 
    }); 

}).then(function (product) { 

    res.send(product); 

}).catch(function (err) { // the power of promise error catching! 
    // If any error occurs in any of the db requests or in the code, this will be called. 
    res.status(400); 
}); 

而且,因爲你正在處理一個數組,.MAP使得這個更容易,消除了內IIFE的需要。

Product.find({'prodType': req.params.type}).lean().exec() 
.then(function (product) { 
    var promises = product.map(function (p) { 
     return Option.find({'prodId': p.productId}).lean().sort({price: -1}).limit(1).exec(function (err, highest) { 

      p.price = highest; 

     })); 
    }); 
    return Promise.all(promises).then(function() { 
     // we want to pass the original product array to the next .then 
     return product; 
    }); 

}).then(function (product) { 

    res.send(product); 

}).catch(function (err) { // the power of promise error catching! 
    // If any error occurs in any of the db requests or in the code, this will be called. 
    res.status(400); 
});