Home > Mobile >  transform multi async call to single
transform multi async call to single

Time:10-22

i have the code which doing multiply requests

const allCategory = [];
     if (Array.isArray(categoryTreeItems.value)) {
       const categoryFilter = [3338, 4775, 3411, 3995, 3949, 2934, 3071, 3462, 3629, 5239];
       categoryFilter.forEach(async (cate) => {
         const {category: categoryData, search: searchCategoriesData} = useCategory('category-data-search');
         await searchCategoriesData({id: cate});
         if (categoryData.value.image_url.length > 0) {
            allCategory.push(categoryData.value);
         }
       });
     }

and i need to send single by 'id:in' any help?

below is part for which it calls categories

<div  v-show="allCategory.length > 0">
   <div >
      <div >
         <p  :style="{color: '#fff'}">{{ "Shop By Category" }}</p>
         <VueSlickCarousel  v-bind="getSettingSlide()">
            <div v-for="(item, idx) in allCategory" :key="idx" >
               <button type="button" @click="pushRouter(item)">
               <img :src="item.image_url" >
               </button>
            </div>
         </VueSlickCarousel>
      </div>
   </div>
</div>

CodePudding user response:

You can use Promise.all() and a map() instead of a forEach.

    const allCategory = [];
    if (Array.isArray(categoryTreeItems.value)) {
      const categoryFilter = [3338, 4775, 3411, 3995, 3949, 2934, 3071, 3462, 3629, 5239];
      await Promise.all(categoryFilter.map(async (cate) => {
        const {category: categoryData, search: searchCategoriesData} = useCategory('category-data-search');
        await searchCategoriesData({id: cate});
        if (categoryData.value.image_url.length > 0) {
          allCategory.push(categoryData.value);
        }
      }));
    }

CodePudding user response:

Reading how an id:'in' works,it seems to me you have to collect the ids in an array & join them with ','.The following should do the trick.

const promises = [];
let ids =[]; // id's to be collected 
let result // result 
if (Array.isArray(categoryTreeItems.value)) {
       const categoryFilter = [3338, 4775, 3411, 3995, 3949, 2934, 3071, 3462, 3629, 5239];
       categoryFilter.forEach((cate) => {
         const {category: categoryData, search: searchCategoriesData} = useCategory('category-data-search');
          ids.push(cate)
         
         if (categoryData.value.image_url.length > 0) {
            allCategory.push(categoryData.value);
         }
       });
      results = await searchCategoriesData({id: `in=${ids.join(',')}`})
     }
  • Related