[axios]then 和 catch 在同一个调用中执行

2024-05-15 989 views
4

我正在打这个电话:

axios.get('/groups', {
  baseURL: 'http://localhost:5000',
  headers: { Authorization: 'Bearer ' + getAccessToken(),  'Content-Type': 'application/json; charset=utf-8' }
})
  .then((response) => {
    console.log('then response',response)
    success(response.data)} )
  .catch((response) => {
    console.log('catch response',response)
    error(response.status, response.data.description)})

我只调用一次。我收到 200 OK 响应,then块执行,并且response是我通常期望的对象。执行之后catch,响应是一个字符串:

TypeError: Cannot read property 'groups' of null(…)

结束语:我的错,这是代码中很远的地方出现的错误,仍在尝试弄清楚它是如何实现承诺的......

回答

0

我有同样的错误。 then 和 catch 在同一个调用中执行

6

我也收到这个错误。对此有解释吗?

8

.catch我也有同样的问题,我的问题与之前的问题有关.then。哎呀。

4

托马斯伍德实际上不应该是这样。 const doRefreshToken = () => { return new Promise( function (resolve,拒绝){ if (成功){ 解析(成功) }else{ 拒绝(错误) } }) }

所以实际上先写 .catch 或 .then 没有任何区别

0

@greenzeal 有区别。这很奇怪,但顺序确实很重要。我想使用像 var func = () => axios.post(....).catch(); 这样的东西在调用此异步函数之前实现错误处理。 func().then(...) 但在这种情况下,“then”回调会在错误(例如 404 状态)时触发,并且“catch”cb 会被忽略。

6

是的,我错了,promise 中有一个顺序。首先使用.然后在.catch之后

7

这恰好发生在我身上,我的问题是(如果我错了,请纠正我)回调中出现的任何类型的错误then()都会被“catch”回调捕获。

例子:

axios.get(url)
    .then( data => {
        //some sort of error
    })
    .catch(error => {
        /it's gonna fall here. If you console log "error" is gonna be the error that happened in the then callback 
    })
8

@dacastro4 谢谢!我费尽心思想弄清楚为什么我的请求在成功后仍然会被抓住。重新阅读我的 .then 并发现一个错误?

3

@dacastro4谢谢你,我的错误是在当时的执行中。修复了then语句调用的函数中的错误,问题解决。

5

@dacastro4 非常感谢你,你就是那个人!

7

我的问题是我不需要 result in then,它被突出显示为未使用,所以我赶紧将其删除并得到以下结果:

    this.processDropFromPalette(data.component, data.dataTransfer.items)
        .then(this.setState(state => {
            data.component.isChanging = 1;
            return { connectedComponents: state.connectedComponents };
        }))
        .catch(reason => {
            this.ctx.publish(new Message.ShowErrorMessage(reason));
        });

并且它不再是 lambda func 声明,.then而是直接函数调用,因此返回this.setState()后立即调用this.processDropFromPalette,无需等待resolve()

3

谢谢。

3

这恰好发生在我身上,我的问题是(如果我错了,请纠正我)回调中出现的任何类型的错误then()都会被“catch”回调捕获。

例子:

axios.get(url)
    .then( data => {
        //some sort of error
    })
    .catch(error => {
        /it's gonna fall here. If you console log "error" is gonna be the error that happened in the then callback 
    })

我看到有几个人对 @dacastro4 的评论竖起大拇指,有人可以解释一下他的评论如何帮助你们解决具体情况吗?我正在查看答案,但我不明白如何使用它来阻止我的.then.catch两者同时执行。

5

这恰好发生在我身上,我的问题是(如果我错了,请纠正我)回调中出现的任何类型的错误then()都会被“catch”回调捕获。例子:

axios.get(url)
    .then( data => {
        //some sort of error
    })
    .catch(error => {
        /it's gonna fall here. If you console log "error" is gonna be the error that happened in the then callback 
    })

我看到有几个人对 @dacastro4 的评论竖起大拇指,有人可以解释一下他的评论如何帮助你们解决具体情况吗?我正在查看答案,但我不明白如何使用它来阻止我的.then.catch两者同时执行。

我认为这意味着可能发生的情况是,“then”块中可能存在错误,因为“catch”块正在执行,这就是两个块都被执行的原因。如果这是真的,在“catch”块中执行 console.log(error) 应该显示详细信息。就我而言,这有助于解决问题。