首页 > 解决方案 > 检查函数回调中的重复

问题描述

现在我已经实现了以下逻辑。有一种方法可以获取购物车中的所有产品,然后通过产品句柄,我浏览每个产品中的标签,如果有我感兴趣的标签,我会得到这个产品(所需的句柄存储在标签中)。

它看起来像这样:

function getDiscountedProduct(callback) {
  var cartContents = fetch('/cart.js')
    .then(response => response.json())
    .then(data => { 
      var item_handles = [];
      var items = data.items;
      for (let i = 0; i < items.length; i++) {
        item_handles.push(items[i].handle)
      }

      return item_handles
    })
    .then(item_handles => {
      if (item_handles.length) {
        for (let i = 0; i < item_handles.length; i++) {
          var products = fetch(`/products/${item_handles[i]}.js`)
          .then(response => response.json())
          .then(product => {
            var tags = product.tags;
            if (tags.length) {
              for (let i = 0; i < tags.length; i++) {
                if (tags[i].includes('discount')) {
                  tags_special = tags[i].split('/');
                  var discount = tags_special[0];
                  var handle = tags_special[1];
                  var discount_percent = tags_special[2];

                  fetch(`/products/${handle}.js`)
                    .then(response => response.json())
                    .then(discounted_product => {
                      callback(discounted_product, discount_percent)
                  });
                }
              }
            }
          })
        }
      }
    })
}

最后,我有一个使用打折产品的回调。它看起来像这样:

getDiscountedProduct(function(product, discount) {
  console.log(product, discount);
})

但我有一个问题。如果购物车中有两个产品指向同一个产品,那么我会显示两次(如果它们不同,那么这是正常的)。我如何以及在什么阶段检查打折产品的独特性?

现在我有想法为每个打折产品提供独特的类,如果它是相同的产品,我会简单地隐藏它。但在我看来,这需要在算法阶段解决。

标签: javascriptasynchronouscallback

解决方案


推荐阅读