簡體   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