喜欢把代码写一行的人

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 handlingreturn {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/

喜欢把代码写一行的人

喜欢把代码写一行的人_我最喜欢的代码行相关推荐

  1. 灵魂的拷问 怎么将代码写得让人无法维护?

    -这文章蛮有意思的,果断选择分享+散播+推广 三连- 程序命名 容易输入的名字.比如:Fred,asdf 单字母的变量名.比如:a,b,c, x,y,z(如果不够用,可以考虑a1,a2,a3,a4,- ...

  2. 喜欢一个讨厌的人_为什么我们喜欢讨厌漫画无人

    喜欢一个讨厌的人 重点 (Top highlight) "Dogs don't talk in Times New Roman." With these immortal word ...

  3. linux下代码写错了怎么更改_谢宝友:手把手教你给Linux内核发patch

    本文简介 本文一步一步的演示如何生成一个简单Linux内核补丁,并提交给Linux社区.用以展示向社区提交补丁的步骤.本文英文名称:<Submit Patches Step by Step> ...

  4. 如何在代码中让按钮高亮_各种博客的代码高亮是如何实现的

    本文来自 「Vue虚拟实验」的小伙伴  余xiaoy,在做 Lovue 项目的时候,他负责了代码高亮显示功能,目前实现了代码高亮.主题切换.某行代码特殊显示.显示行号等功能,效果如下. 下面介绍如何通 ...

  5. 搜索框的代码css,css搜索框_精美css搜索框代码

    摘要 腾兴网为您分享:精美css搜索框代码,追书神器,中日翻译,云南移动,携程等软件知识,以及cdr条码生成器,海风智学中心,东方永夜抄,一起中学老师,飒漫画,天天桌面便签,科学松鼠网,乐蛙,安卓信用 ...

  6. java sapi.spvoice 更改发音人_我最喜欢的几个Java开发工具,推荐8个给你们!

    在Stormpath(一款用户管理和认证服务),我们认真对待质量和效率.任何一个优秀的工匠,仅仅拥有天赋是不够的,你在工作中还需要正确的工具.工程学不仅仅是科学,更是艺术.所以,在Stormpath, ...

  7. python代码写父亲节快乐_用python祝福父亲节_父亲节祝福语 父亲节最感恩温馨的问候语录...

    母爱深似海,父爱重如山.拳拳赤子心,遥遥白发牵.亲恩三春晖,照我一生暖.饮水常思源,路远寄思念.父亲节,惟愿老爸人康安. 有种付出,不计回报,却澄澈永恒,那是父爱:有种牵挂,不计时日,却相伴一生,那也 ...

  8. 中国第一批写java的人_中国java开源界最可爱的人们

    评论 # re: 中国java开源界最可爱的人们 2007-12-07 15:29 sitinspring 如果少一些抒情,多一点实质内容,文章更耐看.  回复  更多评论 # re: 中国java开 ...

  9. python代码写父亲节快乐_父爱如山,深情似海——你的代码像诗一样

    #!/usr/bin/env python import datetime import time class Masterpiece(object): """God m ...

最新文章

  1. 运维中的MySQL数据库管理方式
  2. MVC4将Controller与views分开
  3. mycat 从入门到放弃 (转)
  4. idea中新建.xml文件找不到选项的解决方法
  5. freemarker如何判空容错
  6. 智能合约语言 Solidity 教程系列2 - 地址类型介绍
  7. 2022年危险化学品生产单位安全生产管理人员试题模拟考试平台操作
  8. 带经纬度的水印相机_水印今日相机安卓版下载-水印相机拍照时间地点app下载v2.8.8.14-西西软件下载...
  9. 微信服务号、订阅号和企业号的区别
  10. visual studio 总是和搜狗输入法冲突
  11. 带你快速入门AXI4总线--汇总篇
  12. 【68期分享】7款红色大气PPT模板免费下载
  13. 如何在同一台电脑上保持两个文件夹的内容同步更新?
  14. tp-link 怎么打开ssh服务_如何用Xshell远程连接VPS服务器
  15. 无刷直流电机的PWM调制方式介绍
  16. JS 下载文件方法分享(解决图片文件无法直接下载和 IE兼容问题)
  17. ABAP:增强篇-CJ20N屏幕增强
  18. 微软常用运行库合集 v2020.12.10
  19. 安全考试服务平台app下载地址
  20. PVCBOT【20号】机械螃蟹--横向爬行机器人

热门文章

  1. react-native 常用命令
  2. 样式集,小程序群聊,聊天室样式,效果图
  3. iOS 中 load 和 initialize的实现顺序
  4. ScratchCardView:刮刮卡视图组件
  5. 【H.264/AVC视频编解码技术详解】十九:熵编码算法(5)——H.264的CABAC(上):语法元素的二值化方法...
  6. apache2.2 做后端,增加真实ip到日志中
  7. xml常用操作(js、sql、vb)
  8. Centos下MySQL安装与配置
  9. 秘钥加密码的登录模式
  10. 如何彻底卸载mysql(xp)