【问题标题】:return multiple data on catch block在 catch 块上返回多个数据
【发布时间】:2021-05-27 21:07:38
【问题描述】:

我正在尝试使用 fetch API,我试图返回一个日志获取错误,我所做的是捕获错误并记录捕获捕获的错误,它运行良好,但是当我在上添加更多 console.log catch 块无论 fetch 是否发现错误,它都会执行。为什么会这样?以及如何在 catch 块上返回错误以外的数据?我的代码将对其进行更多解释。提前致谢。

fetch('api', options)
  .then(response => response.json())
  .then(data => console.log(data)
  })
.catch(err =>
  console.log('error', err), //prints error on error 
  console.log("this is test") //print regardless of error(prints everytime the program runs even without error)
);

【问题讨论】:

  • err => 1, f()(err => 1), f(),您正在调用 .catch,并将 console.log 调用作为第二个参数,其中包括调用 console.log

标签: javascript node.js


【解决方案1】:

那是因为没有大括号的箭头函数只能包含一个语句,而另一个console.log被执行并将其返回值传递给.catch。你写的是一样的:

fetch('api', options)
  .then(response => response.json())
  .then(data => console.log(data)
  )
.catch(function(err){ // first argument
    console.log('error', err)
  },
  console.log("this is test") //second argument
)

如果您希望它在 .catch 中执行 only,请改用它:

fetch('api', options)
  .then(response => response.json())
  .then(data => console.log(data)
  )
.catch(err => {
  console.log('error', err), //prints error on error 
  console.log("this is test") //prints only on error
  }
);

【讨论】:

    猜你喜欢
    • 2011-02-11
    • 1970-01-01
    • 2020-12-23
    • 2012-05-18
    • 2016-05-06
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 2016-01-15
    相关资源
    最近更新 更多