簡體   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