繁体   English   中英

在里面分配变量。然后在 map function

[英]Assign variable inside .then in a map function

我正在尝试在 .then function 中分配一个变量.then但我不知道如何在苗条的商店中做到这一点。 我知道它是 promise 并且需要一些时间来分配。

这是代码。

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
                };
            });

其他 function 获取类别:

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

你将不得不等待它

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

由于您具有异步性,因此您需要将代码更改为

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

或者

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);

您必须自己实现 map。 由于 map function 不是异步 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
        }
    });
});

编辑:出于安全原因,将 for 循环转换为 forEach 循环。 阿卜杜勒指出

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM