喜欢把代码写一行的人_我最喜欢的代码行

喜欢把代码写一行的人

Every developer has their favourite patterns, functions or bits of code. This is mine and I use it every day.

每个开发人员都有自己喜欢的模式,功能或代码位。 这是我的,我每天都用。

它是什么? (What is it?)

This little function takes a promise and returns an array of the error and the result of the promise. It’s super simple but can be used for some amazing things.

这个小函数接受一个Promise,并返回错误数组和Promise的结果。 它非常简单,但是可以用于一些令人惊奇的事情。

它能做什么? (What can it do?)

使用异步/等待清理错误处理 (Clean error handling with async / await)

This is the main reason that I use this method every day. At work, we are trying to write all code using async / await syntax for future readability and maintainability. The problem is that awaiting a promise doesn’t tell you if the promise has succeeded or failed.

这是我每天使用此方法的主要原因。 在工作中,我们正在尝试使用async / await语法编写所有代码,以提高可读性和可维护性。 问题在于,等待诺言不会告诉您诺言是成功还是失败。

let unimportantPromiseTask = () => {
    Math.random() > 0.5 ? 
        Promise.reject('random fail') : 
        Promise.resolve('random pass');
};

let data = await unimportantPromiseTask();

If this promise passes then data = ‘random pass', but if it fails then there is an unhandled promise rejection and data is never assigned a value. This may not be what you would expect to happen when reading through the code.

如果此承诺通过,则data = 'random pass' ,但如果失败,则存在未处理的承诺拒绝,并且永远不会为数据分配值。 阅读代码时,这可能不是您期望的。

Passing the promise to this handle function returns a very explicit result which anyone can easily understand when reading it.

将promise传递给此handle函数将返回非常明确的结果,任何人在阅读它时都可以轻松理解。

let [err, res] = await handle(unimportantPromiseTask());

You can then do what you want with the error and result. Here is a common pattern that we often use next:

然后,您可以根据错误和结果执行所需的操作。 这是我们接下来经常使用的常见模式:

if (err 
 (res && !res.data)) { 
    // error handling
    return {err: 'there was an error’}
}
// continue with successful response

The main reason we use this instead of wrapping the awaited promise in a try / catch block is that we find it easier to read.

我们使用此方法而不是将等待的诺言包装在try / catch块中的主要原因是,我们发现它更易于阅读。

停止未处理的诺言拒绝 (Stop unhandled promise rejections)

This function can be used to handle promises (hence the name). Because the function chains .catch onto the promise, if it fails the error is caught. This means if there is a promise that you call and don’t care whether it passes or fails, just pass it into handle!

此功能可用于处理承诺(因此而得名)。 因为该函数将.catch到promise上,所以如果失败,则会捕获错误。 这意味着,如果您有一个承诺要您打电话,而不管它是否通过或失败,只需将其传递给handle

unimportantPromiseTask(); // 50% chance of erroring
handle(unimportantPromiseTask()); // never errors

Without passing the promise into the handle function, there is going to be a chance that it fails. This is increasingly important as future versions of Node are going to terminate the process when an unhandled promise rejection is encountered.

如果没有将promise传递到handle函数中,则可能会失败。 这一点变得越来越重要,因为当遇到未处理的承诺拒绝时,Node的未来版本将终止该过程。

The other ways to handle promise rejections are to wrap the function in a try catch, or just to chain a .catch onto the promise. Whilst these are both very valid, using handle where we can makes our code more consistent.

处理承诺拒绝的其他方法是将函数包装在try catch中,或仅将.catch到promise。 虽然它们都是非常有效的,但是使用handle可以使我们的代码更加一致。

Thanks for reading this quick post on my favourite line of code. If you’ve got a favourite line of code, let me know in the comments what it is and why!

感谢您阅读我最喜欢的代码行中的这篇快速文章。 如果您有喜欢的代码行,请在注释中告诉我它是什么以及为什么!

翻译自: https://www.freecodecamp.org/news/my-favourite-line-of-code-53627668aab4/

喜欢把代码写一行的人