【问题标题】:Axios Promise Resolution / Pending PromiseAxios 承诺解决/待处理承诺
【发布时间】:2022-01-22 07:04:15
【问题描述】:

关于 JS 中的承诺解决,我有以下问题。

前端代码:

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);
    }
  };

后端python代码:

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

在我的控制台中显示*Promise {<pending>}*,但从未“收到”。这是为什么?如何等待后端的响应?

【问题讨论】:

  • 您是否测试了后端路由本身?它适用于卷曲吗?顺便说一句,你能试试 async/await 吗?
  • 嗨,是的,我现在还添加了“GET”作为方法:❯ curl -X GET "localhost:5000/auth/test" 返回 {"msg":"Test Request"}
  • 好的。尝试使用 axios.get().then().catch(); (没有尝试捕获)。或者尝试使用 async/await。
  • 这似乎也不起作用:( ``` const test = async () => { await axios.get("localhost:5000/auth/test").then( (res) => { console.log("收到") console.log(res) }).catch(err => { console.error(err); }); }; ``
  • Http 方法应该是POST 而不是GET

标签: javascript axios es6-promise


【解决方案1】:

您的代码将无法工作,因为 try/carch 块仅从等待的承诺中捕获错误。

因为await关键字悬念承诺并从中返回值。

这与您收到Promise {<pending>} 消息的原因相同。

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

【讨论】:

  • 感谢您的回答。我以前有这个,但我不再使用这个版本得到任何日志或消息。 IDK,也许我在 React 的不同地方做错了什么
  • 我用一个全新的 react 项目对此进行了测试。以上工作。
猜你喜欢
  • 2020-12-20
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 2019-04-29
  • 2018-04-02
  • 1970-01-01
  • 2017-04-04
相关资源
最近更新 更多