[Vuejs]-Transform multi async call to single

1πŸ‘

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);
        }
      }));
    }
πŸ‘€Spoke44

0πŸ‘

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(',')}`})
     }
πŸ‘€anuragb26

Leave a comment