【问题标题】:why does the .then run before the resolve function here? [duplicate]为什么 .then 在这里的 resolve 函数之前运行? [复制]
【发布时间】:2019-12-09 15:24:28
【问题描述】:

我有这段代码,如果我注释掉 .then 部分,帖子工作得很好,但如果我把它留在里面,帖子就不会通过。我该如何解决这个问题?

      axios.post('http://localhost:5000/exercises/add', exercise)
                .then(res => console.log(res.data))
                .then(window.location.href = '/')
                .catch(err => console.log(err))

【问题讨论】:

  • 因为你那里有一个语句..它会被预先执行..将它包装在像then(function(){window.location.href='/';})这样的函数中

标签: javascript


【解决方案1】:

window.location.href = '/' 不是函数

立即对其进行评估,并将结果传递给then()(因为结果不是函数,所以这是无用的)。

做你在上一行所做的:

  axios.post('http://localhost:5000/exercises/add', exercise)
        .then(res => console.log(res.data))
        .then(log_result => (window.location.href = '/'))
        .catch(err => console.log(err))

更好的是,因为你没有从console.log 得到承诺,所以只需要一个then()

  axios.post('http://localhost:5000/exercises/add', exercise)
        .then(res => {
            console.log(res.data);
            window.location.href = '/';
        })
        .catch(err => console.log(err))

【讨论】:

    【解决方案2】:

    您有 2 个 then 出于某种不需要的原因。尝试将两者结合在一起

    axios.post('http://localhost:5000/exercises/add', exercise)
      .then(res => {
        console.log(res.data)
        window.location.href = '/'
      })
      .catch(err => console.log(err))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2017-04-07
      • 2021-12-27
      • 2019-02-22
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多