为什么“.catch(err => console.error(err))”气馁? [英] Why is `.catch(err => console.error(err))` discouraged?

查看:606
本文介绍了为什么“.catch(err => console.error(err))”气馁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用promises并且代码如下所示:

I'm using promises and have code that looks like the following:

function getStuff() { 
  return fetchStuff().then(stuff => 
    process(stuff)
  ).catch(err => {
    console.error(err);
  });
}

或:

async function getStuff() { 
  try {
    const stuff = await fetchStuff();
    return process(stuff);
  } catch (err) { 
    console.error(err);
  }
}

我这样做是为了避免错误,但是一位用户告诉我,我不应这样做而且不赞成。

I was doing this to avoid missing on errors but was told by a fellow user that I shouldn't be doing this and it is frowned upon.


  • 有什么问题> return ... .catch(err => console.error(err))

  • 我见过很多这样做的代码,为什么?

  • 我该怎么办?

推荐答案

为什么旧代码会这样做吗?



从历史上看,较早的(2013年之前)承诺图书馆吞噬未经处理的承诺拒绝,而你自己没有处理过。从那以后的任何事情都不是这样。

Why does old code do this?

Historically, older (pre 2013) promise libraries 'swallowed' unhandled promise rejections you have not handled yourself. This has not been the case in anything written since then.

浏览器和节点。 js已经自动记录未被捕获的承诺拒绝或有处理它们的行为,并会自动记录它们。

Browsers and Node.js already automatically log uncaught promise rejections or have behaviour for handling them and will log them automatically.

此外 - 通过添加 .catch 你发信号通知调用 undefined 的函数的方法:

Moreover - by adding the .catch you are signalling to the method calling the function that undefined is returned:

// undefined if there was an error
getStuff().then(stuff => console.log(stuff)); 

编写异步代码时应该问自己的问题通常是同步版本是什么?代码吗?:

The question one should be asking oneself when writing async code is usually "what would the synchronous version of the code do?":

function calculate() { 
  try {
    const stuff = generateStuff();
    return process(stuff);
  } catch (err) { 
    console.error(err);
    // now it's clear that this function is 'swallowing' the error.
  }
}

我不认为消费者会期望这个功能返回 undefined 如果发生错误。

I don't think a consumer would expect this function to return undefined if an error occurs.

总而言之 - 这是令人不悦的,因为它让开发人员感到惊讶在应用程序流程和浏览器中,无论如何都记录未被捕获的承诺错误。

So to sum things up - it is frowned upon because it surprises developers in the application flow and browsers log uncaught promise errors anyway today.

没什么。这就是它的美丽 - 如果你写的:

Nothing. That's the beauty of it - if you wrote:

async function getStuff() { 
  const stuff = await fetchStuff();
  return process(stuff);
}
// or without async/await
const getStuff = fetchStuff().then(process);

首先,你会在周围得到更好的错误 :)

旧版本的Node .js可能不会记录错误或显示弃用警告。在这些版本中,您可以使用 console.error (或正确的日志记录工具)全球

Old versions of Node.js might not log errors or show a deprecation warning. In those versions you can use console.error (or proper logging instrumentation) globally:

// or throw to stop on errors
process.on('unhandledRejection', e => console.error(e));

这篇关于为什么“.catch(err => console.error(err))”气馁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆