Reputation: 2105
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!
Upvotes: 0
Views: 2548
Reputation: 664548
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;
}
});
Upvotes: 3
Reputation: 73
Use resolve() instead of return.
if(r && r.data && r.data.result) {
resolve({productId: r.data.result});
}
Upvotes: 1