[英]Assign variable inside .then in a map function
I'm trying to assign a variable inside a .then
function but I don't know how to do that in svelte store.我正在尝试在 .then function 中分配一个变量
.then
但我不知道如何在苗条的商店中做到这一点。 I know that its a promise and takes some time to be assigned.我知道它是 promise 并且需要一些时间来分配。
Here is the code.这是代码。
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
};
});
getProductCategory: async (id, token) => {
const res = await api.get(`backoffice/v1/category/${id}`, token);
return res?.category?.name;
},
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
};
}));
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);
You will have to do you own map implementation.您必须自己实现 map。 Since the map function is not an async function.
由于 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
}
});
});
EDIT: Convert for loop to forEach loop for security reasons.编辑:出于安全原因,将 for 循环转换为 forEach 循环。 pointed by Abdel
阿卜杜勒指出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.