提问者:小点点

异步回调array.map()


几周前刚开始学Node.js....我不明白为什么“products”数组包含null而不是所需的对象....

在第13行,当我对对象进行控制台日志记录时,我得到了所需的对象,但我不明白当我在map函数完成它的执行后在第40行对它们进行控制台日志记录时,它们为什么是空的....

如果数组长度是2(这意味着推入成功),为什么里面存储的对象仍然是空的,而不是我想要存储的对象?

控制台输出

订单模式

exports.getOrders = async (req, res, next) => {
  const userOrders = [];
  Order.find({ 'user.userId': req.user._id }).then((orders) => {
    console.log(orders); // Line 4
    async.eachSeries(
      orders,
      function (order, callback) {
        const products = order.products.map((p) => {
          const seriesId = p.product.seriesId;
          const volumeId = p.product.volumeId;
          Series.findById(seriesId).then((series) => {
            const volume = series.volumes.id(volumeId);
            console.log(volume, p.quantity); // Line 13
            return {
              seriesTitle: volume.parent().title,
              volume: volume,
              quantity: p.quantity
            };
          });
        });
        console.log('Product Array Length: ', products.length); // Line 21
        if (products.length !== 0) {
          const data = {
            productData: products,
            orderData: {
              date: order.date,
              totalPrice: order.totalPrice
            }
          };
          userOrders.push(data);
          callback(null);
        } else {
          callback('Failed');
        }
      },
      function (err) {
        if (err) {
          console.log('Could not retrieve orders'); 
        } else {
          console.log(userOrders);  // Line 40
          res.render('shop/orders', {
            docTitle: 'My Orders',
            path: 'orders',
            orders: userOrders,
            user: req.user
          });
        }
      }
    );
  });
};

共1个答案

匿名用户

在第8行,order.products.map返回一个数组null。因为这是一个异步映射。对于每个产品,您都调用series.findbyid,这是一个承诺,它只在解析时返回值。因为您不是在等待承诺的解决,所以它在每次迭代时都返回null。

您必须首先映射所有的承诺,然后调用promise.all来解析它们,然后,您将得到期望值。

null

exports.getOrders = async (req, res, next) => {
  const userOrders = [];
  Order.find({ 'user.userId': req.user._id }).then((orders) => {
    console.log(orders); // Line 4
    async.eachSeries(
      orders,
      function (order, callback) {
        const productPromise = order.products.map((p) => {
          const seriesId = p.product.seriesId;
          const volumeId = p.product.volumeId;
          //ANSWER:  Return the following promise
          return Series.findById(seriesId).then((series) => {
            const volume = series.volumes.id(volumeId);
            console.log(volume, p.quantity); // Line 13
            return {
              seriesTitle: volume.parent().title,
              volume: volume,
              quantity: p.quantity
            };
          });
        });
        // ANSWER: call all the promises
        Promise.all(productPromise)
        .then(function(products) {
            console.log('Product Array Length: ', products.length);
            if (products.length !== 0) {
            const data = {
              productData: products,
              orderData: {
                date: order.date,
                totalPrice: order.totalPrice
              }
            };
            userOrders.push(data);
            callback(null);
          } else {
            callback('Failed');
          }
        });
      },
      function (err) {
        if (err) {
          console.log('Could not retrieve orders'); 
        } else {
          console.log(userOrders);  // Line 40
          res.render('shop/orders', {
            docTitle: 'My Orders',
            path: 'orders',
            orders: userOrders,
            user: req.user
          });
        }
      }
    );
  });
};

相关问题