繁体   English   中英

Array.map() 的异步回调

[英]Asynchronous Callback to Array.map()

几周前我刚刚开始学习 Node.js ......我无法理解为什么“产品”数组包含null而不是所需的对象......

On Line 13, when I am console logging the object, I get the desired object but I don't understand why they are null when I console log them on Line 40 after the map function has completed it's execution....

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

控制台 Output

控制台输出

订单模式

订单模式

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

在第 8 行, order.products.map返回 null 数组。 因为这是一个异步映射。 对于每个产品,您都在调用Series.findById ,它是一个 promise ,它只在解析时返回值。 由于您没有等待 promise 解决,因此它在每次迭代时返回 null。

您必须首先 map 所有的承诺,然后调用Promise.all来解决它们,然后,您将获得预期的价值。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM