Search code examples
javascriptaxioses6-promise

Axios Promise Resolution / Pending Promise


I have the following issue, regarding promise resolution in JS.

Frontend code:

const test = () => {
    try {
      let response = axios.post("http://localhost:5000/auth/test").then(
        (res) => {
          console.log("received")
          console.log(res)
      });
      console.log(response);
    } catch (error) {
      console.error(error);
    }
  };

Backend python code:

@auth.route("/test", methods=["POST"])
def test():
    import time
    time.sleep(0.5)
    return jsonify("Test Request"), 200

In my console it says *Promise {<pending>}* but never "received". Why is that? How can I await the response of the backend?


Solution

  • You code wouldn't work, Because try/carch block only catch errors from awaited promise.

    Because await keyword suspense promise and return value from it.

    This is the same reason you got Promise {<pending>} message.

    async function test() {
      try {
        let response = await axios.post("http://localhost:5000/auth/test");
        console.log(response);
      } catch (error) {
        console.error(error);
      }
    }