0

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!

LakiGeri
  • 2,046
  • 6
  • 30
  • 56

2 Answers2

3

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;
    }
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks for your response! I'm going to give it a chance. – LakiGeri Apr 12 '18 at 07:15
  • My challenge has been when axios does not pass up the "then" chain value properly to the caller's then() handler (added on the returned promise object. Instead it always returns the entire raw "response" which seems like a bug or the additional handler is not defined due to a race condition? The above example only does everything inline. – justdan23 Aug 27 '20 at 18:51
  • @justdan23 You might want to [ask a new question](https://stackoverflow.com/questions/ask) with an [mcve] – Bergi Aug 27 '20 at 19:39
1

Use resolve() instead of return.

if(r && r.data && r.data.result) {
  resolve({productId: r.data.result});
} 
  • 1
    There is no need for `new Promise` in the first place as `axios.post` already returns a promise. – str Apr 11 '18 at 15:10