I want to send multiple PUT requests in one method but I do not know if it's possible, because all the documentation and answers on SO are only for GET requests.
// vue script, this is one PUT request
updateProduct() {
const config = {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`
},
};
axios
.put(
"myapihere.com" +
this.$route.params.id,
{
name: this.name,
},
config
)
.then(async (res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
},
I want to add 2 more PUT requests in the updateProduct method. Is it possible to use Promise.all? and then how do I send the body to each corresponding URL? Appreciate all help, thank you.
// vue script, this is one PUT request
updateProduct() {
const config = {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
"Content-Type": "application/json"
},
};
// lets say you wanna use the following data to send to 3 requests
const allNames = ["name1", "name2", "name3"];
// following lets say your url params that are corresponding to your eachrequests
const allParamIds = ["11","12","13"]
const allRequests = allNames.map((eachName, index) => {
const currentName = eachName;
const currentParamId = allParamsIds[index]
const currentUrl = `myapihere.com/${currentParamId}`
// you have to return as a promise
return axios.put(currentUrl, body: JSON.stringify({name: currentName}), config)
})
// Promise.all() takes an array as argument, allRequests is an array
Promise.all(allRequests)
.then((response) => {
// response will be an array
console.log("response is", response);
})
.catch(err => console.error(err))
},
Let me know if it worked for you or not!