I made a axios post call in a Promise, and I want to get the ajax respone in the Promise then method.
return new Promise((resolve, reject) => {
axios.post('/api/products/modify', product).
then(r => {
if(r && r.data && r.data.result) {
return {productId: r.data.result};
} else {
console.error("actions addproduct error occours during modifying the product! Error: " + r.data.error);
reject(r.data.error);
}
}).
catch((error) => {
console.error("actions addproduct; error occours during adding the product! Error: " + error);
reject(error);
});
}
});
And when I call p.then();
I want to get the {productId: r.data.result}
object.
I tried this:
p.then(r => {
console.debug("response: " + r);
});
But does not work. However the ajax call is reaching the server, so the promise works, but I can not add the result to the then method.
Thx for the response in advance!
Avoid the Promise
constructor antipattern! The return
you had was fine, but you should simply throw
your errors and then use the promise that then()
already creates for you:
return axios.post('/api/products/modify', product).then(r => {
if (r && r.data && r.data.result) {
return {productId: r.data.result};
} else {
console.error("actions addproduct error occours during modifying the product! Error: " + r.data.error);
throw r.data.error;
}
}, error => {
console.error("actions addproduct; error occours during adding the product! Error: " + error);
throw error;
});
Or without the logs:
return axios.post('/api/products/modify', product).then(r => {
if (r.data.result) {
return {productId: r.data.result};
} else {
throw r.data.error;
}
});