我遇到了redux thunk的问题。
在动作创建器中,我首先创建一个图像对象并从数据库中获取image_id
。
我有一个名为clients
的var,它是需要图像ID的所有客户端ID的列表。 [1,2,3,4,5]
我通过for循环,使用axios.get获取客户端,然后将新的image_id添加到客户端字段的图像列表中。
然后我将新的更改添加到字段client_images
中的客户端。
export function addNewClient(imageData, clients) {
return function(dispatch) {
axios.post(`${API_URL}/media`, fileData, { withCredentials: true, headers: { 'Content-Type': 'multipart/form-data' } })
.then(response => {
var image_id = response.data.id;
//go through each client to get current background list
for (var i = 0; i < clients.length; i++) {
var currRow = clients[i];
console.log("GETTING NEW CLIENT", currRow)
axios.get(`${API_URL}/clients/${currRow}`, { withCredentials: true })
.then(response => {
var currImages = response.data.client_images;
var clientImages = [...currImages, image_id];
console.log("ADDING NEW CLIENT IMAGE IDs", currRow);
axios.put(`${API_URL}/clients/${currRow}`, {client_images:clientImages}, { withCredentials: true })
})
.catch(() => {
console.log("Can't set image list to clients");
});
}
});
}
}
我的问题在于: 在我可以调用
之前完成整个for循环axios.put(`${API_URL}/clients/${currRow}`, {client_images:clientImages}, { withCredentials: true })
在我的控制台中,这是输出
如您所见,添加新客户端映像仅在for循环完成后调用。我需要将“添加新客户端映像”调用INSIDE for for循环,以便可以调用其他axios函数,而不是将其调用5次到id为5的客户端。
有没有办法让for循环在redux thunk中运行?
答案 0 :(得分:3)
啊这个人一开始总是很棘手。将promises与数组一起使用时,请使用array.map
而不是for循环。所以尝试改变这个:
for (var i = 0; i < clients.length; i++) {
var currRow = clients[i];
axios.get(`${API_URL}/clients/${currRow}`, { withCredentials: true })
// ...
}
对此:
return Promise.all(clients.map(function(currRow){
return axios.get(`${API_URL}/clients/${currRow}`, { withCredentials: true })
// ...
}));
这将确保所有承诺都有自己的范围。
所以最终的结果是:
export function addNewClient(imageData, clients) {
return function(dispatch) {
axios.post(`${API_URL}/media`, fileData, { withCredentials: true, headers: { 'Content-Type': 'multipart/form-data' } })
.then(response => {
var image_id = response.data.id;
//go through each client to get current background list
return Promise.all(clients.map(function(currRow){
console.log("GETTING NEW CLIENT", currRow)
return axios.get(`${API_URL}/clients/${currRow}`, { withCredentials: true })
.then(response => {
var currImages = response.data.client_images;
var clientImages = [...currImages, image_id];
console.log("ADDING NEW CLIENT IMAGE IDs", currRow);
return axios.put(`${API_URL}/clients/${currRow}`, {client_images:clientImages}, { withCredentials: true })
})
.catch(() => {
console.log("Can't set image list to clients");
});
}));
});
}
}