喜欢把代码写一行的人_我最喜欢的代码行
喜欢把代码写一行的人
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/
喜欢把代码写一行的人
相关文章:

智能家居APP开发
智能家居APP开发 APP开发技术qq交流群:347072638 前言,随着智能硬件设备的流行,智能家居開始红火,智能家居就是家用电器的智能化。包含智能锁,灯,空调,灯,音箱等等,移动设…

android小技巧(二)
一、如何控制Android LED等?(设置NotificationManager的一些参数) 代码如下: final int ID_LED19871103; NotificationManager nm(NotificationManager)getSystemService(NOTIFICATION_SERVICE); Notification notification new Notification(); notificatio…

JS 验证表单不能为空
开发交流QQ群: 173683895 173683895 526474645 人满的请加其它群 JS 验证表单不能为空的简单demo,先看效果图 实现代码 <!--index.wxml--> <form classform bindsubmitformSubmit bindresetformReset><input namename value{{name}} placeho…

周末不用过来了,好好休息吧_如何好好休息
周末不用过来了,好好休息吧When I wrote about my productive routine in a previous article, I said I’d work for 1.5 hours and take a break for 30 minutes. And I’d repeat this sequence four times a day.当我在上一篇文章中谈到生产性例程时,…

HTML实现折现图完整源码及效果图
开发交流QQ群: 173683895 173683895 526474645 人满的请加其它群 效果图 源码 <!DOCTYPE html> <html><head><meta charset"utf-8" /><script src"https://cdnjs.cloudflare.com/ajax/libs/echarts/4.2.1/echarts-en.common…

Date类(java.util)和SimpleDateFormat类(java.text)
在程序开发中,经常需要处理日期和时间的相关数据,此时我们可以使用 java.util 包中的 Date 类。这个类最主要的作用就是获取当前时间,我们来看下 Date 类的使用: 使用 Date 类的默认无参构造方法创建出的对象就代表当前时间&#…

8月12笔记-安卓文件扫描
Android的文件系统 1.Android的项目是运行在Linux操作系统上的 2.Linux的文件系统根目录是/,Windows只有某个盘符根目录 3.mnt文件夹是手机的内存卡根目录,此目录是安卓开发经常使用的 4.在windows下,最高管理员叫做Administrator,…

可视化编码_Modulz简介:可视编码的下一步
可视化编码by Colm Tuite通过Colm Tuite Modulz简介:可视编码的下一步 (Introducing Modulz: The Next Step in Visual Coding) Modulz is a visual code editor for designing and building digital products — without writing code. Last week, we launched ou…

SQL执行过程中的性能负载点
一、SQL执行过程 1、用户连接数据库,执行SQL语句; 2、先在内存进行内存读,找到了所需数据就直接交给用户工作空间; 3、内存读失败,也就说在内存中没找到支持SQL所需数据,就进行物理读,也就是到磁…

认识Backbone (五)
Backbone.Router(路由)/ Backbone.history(历史) Backbone.Router 为客户端路由提供了许多方法,并能连接到指定的动作(actions)和事件(events)。 对于不支持 History API…

if else 你以为你把它吃透了吗?我让你惊讶一下
开发交流QQ群: 173683895 173683895 526474645 人满的请加其它群 if 和 else 是写代码最常用的,但是往往同学们不会去深入的了解他,这里我写几个Demo玩玩。 首先简单列一下什么值会返回true , 什么值会返回false。 示例:…

router路由react_使用React Router在React中受保护的路由
router路由reactIn this video, you will see how to create a protected route using React Router. This route is accessible only when the user is logged in.在此视频中,您将看到如何使用React Router创建受保护的路由。 仅当用户登录时,此路由才可…

SSH框架搭建笔记
1、建立一个web项目,设置编码格式,建立src下的包,建立资源文件夹 2、加入Spring运行必须的jar包(5个jar包)spring-beans-4.1.4.RELEASE.jarspring-context-4.1.4.RELEASE.jarspring-core-4.1.4.RELEASE.jarspring-expression-4.1.4.RELEASE.j…

灵活运用 SQL SERVER FOR XML PATH
FOR XML PATH 有的人可能知道有的人可能不知道,其实它就是将查询结果集以XML形式展现,有了它我们可以简化我们的查询语句实现一些以前可能需要借助函数活存储过程来完成的工作。那么以一个实例为主. 一.FOR XML PATH 简单介绍 那么还是首先来介绍一下FOR…

小程序画布,随机24个数显示在画布上面,不可重叠
QQ技术交流群 173683866 526474645 欢迎加入交流讨论,打广告的一律飞机票 效果图(下面两个图都是随机显示24的圆圈在画布上面) 实现代码 <!--pages/test2/test2.wxml--> <canvas style"width: 100%; height:700rpx;" ca…

hacktoberfest_Hacktoberfest 2018:如何获得免费衬衫—即使您是编码新手
hacktoberfestEvery October, Digital Ocean and GitHub ship out free Hacktoberfest shirts to thousands of people around the world.每年10月,Digital Ocean和GitHub都会向全球成千上万的人运送免费的Hacktoberfest衬衫。 I’ve gotten Hacktoberfest shirts …

Android自动化测试框架
1、Monkeyrunner:优点:操作最为简单,可以录制测试脚本,可视化操作;缺点:主要生成坐标的自动化操作,移植性不强,功能最为局限; 2、Rubotium:主要针对某一个…

详解 Date 对象
JS使用Date对象来处理日期和时间 五种调用Date函数的方式 Date() 单纯的作为函数调用,传入的参数会被忽略,返回当前日期和时间的字符串表示。 new Date() 作为构造函数调用。 返回当前日期和时间的Date对象。 new Date(Milliseconds) 作为构造函数调用…

Bootstrap select 多选并获取选中的值
QQ技术交流群 173683866 526474645 欢迎加入交流讨论,打广告的一律飞机票 效果图: 输出日志 代码: <!DOCTYPE html> <html><head><meta charset"UTF-8"><script src"js/jquery-3.4.1.min.js&quo…

如何在React中使用Typescript
TypeScript can be very helpful to React developers.TypeScript对React开发人员可能非常有帮助。 In this video, Ben Awad teaches how to use Typescript in React and shares some of its benafits. He also tells about a great boilerplate for TypeScript React proje…

java web 开发应用 ----过滤器
过滤器的作用 1.当用户请求web资源时,如果没有过滤器,用户可以直接获取到这个web资源,当有了过滤器之后,当用户请求web资源时,web容器中的过滤器先会拦截到这个请求,然后根据这个请求 做相应的处理…

小程序在wxml使用indexOf
QQ技术交流群 173683866 526474645 欢迎加入交流讨论,打广告的一律飞机票 demo场景: 有两个数组,页面渲染一个数组1,数组2中有数组1随机下标的值,判断数组1是否包含数组2的值,如果包含了就改变当前下标的…

d3.js图表_如何使用D3.js建立历史价格图表
d3.js图表逐步可视化财务数据集的方法 (A step by step approach towards visualizing financial datasets) It is a challenge to communicate data and display these visualizations on multiple devices and platforms.交流数据并在多个设备和平台上显示这些可视化内容是一…

Harris角点
可参考:http://www.cnblogs.com/ronny/p/4009425.html http://www.cnblogs.com/ztfei/archive/2012/05/07/2487123.html http://blog.csdn.net/crzy_sparrow/article/details/7391511 矩阵M(x)的特征值能表示在水平和竖直方向的变化程度,但Harris给出的角…

【博客美化】公告栏显示个性时间
设置侧边公告栏显示个性化时间 效果图: <div id"myTime"><object classid"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version8,0,0,0"…

微信小程序实现退款
QQ技术交流群 173683866 526474645 欢迎加入交流讨论,打广告的一律飞机票 退款php代码 <?php // ---------------------------------------------------------------------- // | Tplay [ WE ONLY DO WHAT IS NECESSARY ] // -------------------------------…

firebase 发生消息_如何在命令行提示符下显示当前的Firebase项目名称,以防止发生危险错误...
firebase 发生消息by Thang Minh VuThang Minh Vu 如何在命令行提示符下显示当前的Firebase项目名称,以防止发生危险错误 (How to show your current Firebase project name on the command line prompt to prevent dangerous errors) When working on a project w…

使用SQLite删除Mac OS X 中launchpad里的快捷方式
一般情况下,从App Store安装的应用程序,如果应用删除,那么launchpad里对应的图标会一起删除了。 而对于不是通过App Store安装的应用程序,删除应用程序,Launchpad中很可能仍然留有相关程序图标。不能忍!是要…

php传递JSON数据
QQ技术交流群 173683866 526474645 欢迎加入交流讨论,打广告的一律飞机票 php代码 public function ttt(){$data request()->param();$refund_fee $data[total_fee];$refund_phone $data[refund_phone];// consignee-金额;number-电话号码&a…

中国制造2025+互联网+,引领制造业发展
"中国制造2025""互联网",引领制造业发展转载于:https://www.cnblogs.com/DTWolf/p/4733568.html