【问题标题】:Why is this promise resolving early?为什么这个承诺会提前解决?
【发布时间】:2015-11-10 12:40:44
【问题描述】:

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);

});

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    将所有代码从 .exec() 回调移动到 .then,并返回一个新的 Promise,当所有其他 Promise 完成时,它会解析。

    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);
    });
    

    【讨论】:

      猜你喜欢
      • 2015-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 2021-12-22
      • 1970-01-01
      • 2019-05-23
      • 2020-10-25
      相关资源
      最近更新 更多