Home > Software design >  Assign variable inside .then in a map function
Assign variable inside .then in a map function

Time:08-12

Im trying to assign a variable inside a .then function but i dont know how to do that in svelte store. I know that its a promise and takes some time to be assigned.

Here is the code.

The map function

data.products.data = data?.products?.data?.map((item) => {
                let category = '';
                customPIMListStore.getProductCategory(item.productCategoryId, token).then((data) => {
                    category = data;
                    console.log('category inside', category);
                });
                return {
                    ...item,
                    category
                };
            });

The other function to get the category

getProductCategory: async (id, token) => {
        const res = await api.get(`backoffice/v1/category/${id}`, token);
        return res?.category?.name;
    },

CodePudding user response:

You will have to await for it

data.products.data = await Promise.all(data?.products?.data?.map(async (item) => {
  const category = customPIMListStore.getProductCategory(item.productCategoryId, token)
  return {
    ...item,
    category
  };
}));

CodePudding user response:

Since you have asynchrony, you'll need to change your code to

data.products.data = await Promise.all(data?.products?.data?.map(async (item) => {
    const category = await customPIMListStore.getProductCategory(item.productCategoryId, token);
    return {
        ...item,
        category
    };
}));

or

Promise.all(data?.products?.data?.map(async (item) => {
    const category = await customPIMListStore.getProductCategory(item.productCategoryId, token);
    return {
        ...item,
        category
    };
})).then(result => data.products.data = result);

CodePudding user response:

You will have to do you own map implementation. Since the map function is not an async function.

productsData.forEach((item, i) => {
    let category = '';
    customPIMListStore.getProductCategory(item.productCategoryId, token).then((data) => {
        category = data;
        console.log('category inside', category);

        productsData[i] = {
            ...item,
            category
        }
    });
});

EDIT: Convert for loop to forEach loop for security reasons. pointed by Abdel

  • Related