当前位置: 首页 > 编程日记 > 正文

promise 和 async await区别

 什么是Async/Await?

async/await是写异步代码的新方式,以前的方法有回调函数和Promise。
  async/await是基于Promise实现的,它不能用于普通的回调函数。
  async/await与Promise一样,是非阻塞的。
  async/await使得异步代码看起来像同步代码,这正是它的魔力所在。

 Async/Await语法

 假设函数getJSON返回值是 Promise,并且 Promise resolves 有一些JSON 对象。我们只想调用它并且记录该JSON并且返回完成。

1)使用Promise:

复制代码

    const makeRequest = () =>getJSON().then(data => {console.log(data)return "done"})makeRequest()

复制代码

2)使用Async:

复制代码

    const makeRequest = async () => {// await getJSON()表示console.log会等到getJSON的promise成功reosolve之后再执行。console.log(await getJSON)return "done"}makeRequest()

复制代码

 区别:

1)函数前面多了一个aync关键字。await关键字只能用在aync定义的函数内。async函数会隐式地返回一个promise,该promise的reosolve值就是函数return的值。(示例中reosolve值就是字符串”done”)
  2)第1点暗示我们不能在最外层代码中使用await,因为不在async函数内。例如:

复制代码

    // 不能在最外层代码中使用awaitawait makeRequest()// 这是会出事情的 makeRequest().then((result) => {// 代码})

复制代码

为什么Async/Await更好?

1)使用async函数可以让代码简洁很多,不需要像Promise一样需要些then,不需要写匿名函数处理Promise的resolve值,也不需要定义多余的data变量,还避免了嵌套代码。

2) 错误处理:
    Async/Await 让 try/catch 可以同时处理同步和异步错误。在下面的promise示例中,try/catch 不能处理 JSON.parse 的错误,因为它在Promise中。我们需要使用 .catch,这样错误处理代码非常冗余。并且,在我们的实际生产代码会更加复杂。

复制代码

    const makeRequest = () => {try {getJSON().then(result => {// JSON.parse可能会出错const data = JSON.parse(result)console.log(data)})// 取消注释,处理异步代码的错误// .catch((err) => {//   console.log(err)// })} catch (err) {console.log(err)}}

复制代码

使用aync/await的话,catch能处理JSON.parse错误:

复制代码

    const makeRequest = async () => {try {// this parse may failconst data = JSON.parse(await getJSON())console.log(data)} catch (err) {console.log(err)}}

复制代码

3)条件语句
    条件语句也和错误捕获是一样的,在 Async 中也可以像平时一般使用条件语句

Promise:

复制代码

    const makeRequest = () => {return getJSON().then(data => {if (data.needsAnotherRequest) {return makeAnotherRequest(data).then(moreData => {console.log(moreData)return moreData})} else {console.log(data)return data}})}

复制代码

Async/Await:

复制代码

    const makeRequest = async () => {const data = await getJSON()if (data.needsAnotherRequest) {const moreData = await makeAnotherRequest(data);console.log(moreData)return moreData} else {console.log(data)return data}}

复制代码

4)中间值
    你很可能遇到过这样的场景,调用promise1,使用promise1返回的结果去调用promise2,然后使用两者的结果去调用promise3。

复制代码

    const makeRequest = () => {return promise1().then(value1 => {return promise2(value1).then(value2 => {return promise3(value1, value2)})})}

复制代码

如果 promise3 不需要 value1,嵌套将会变得简单。如果你忍受不了嵌套,你可以将value 1 & 2 放进Promise.all来避免深层嵌套,但是这种方法为了可读性牺牲了语义。除了避免嵌套,并没有其他理由将value1和value2放在一个数组中。

复制代码

    const makeRequest = () => {return promise1().then(value1 => {return Promise.all([value1, promise2(value1)])}).then(([value1, value2]) => {return promise3(value1, value2)})}

复制代码

使用async/await的话,代码会变得异常简单和直观。

    const makeRequest = async () => {const value1 = await promise1()const value2 = await promise2(value1)return promise3(value1, value2)}

5)错误栈
     如果 Promise 连续调用,对于错误的处理是很麻烦的。你无法知道错误出在哪里。

复制代码

    const makeRequest = () => {return callAPromise().then(() => callAPromise()).then(() => callAPromise()).then(() => callAPromise()).then(() => callAPromise()).then(() => {throw new Error("oops");})}makeRequest().catch(err => {console.log(err);// output// Error: oops at callAPromise.then.then.then.then.then (index.js:8:13)})

复制代码

async/await中的错误栈会指向错误所在的函数。在开发环境中,这一点优势并不大。但是,当你分析生产环境的错误日志时,它将非常有用。这时,知道错误发生在makeRequest比知道错误发生在then链中要好。

复制代码

    const makeRequest = async () => {await callAPromise()await callAPromise()await callAPromise()await callAPromise()await callAPromise()throw new Error("oops");}makeRequest().catch(err => {console.log(err);// output// Error: oops at makeRequest (index.js:7:9)})

复制代码

6)调试
     async/await能够使得代码调试更简单。2个理由使得调试Promise变得非常痛苦:

《1》不能在返回表达式的箭头函数中设置断点
   《2》如果你在.then代码块中设置断点,使用Step Over快捷键,调试器不会跳到下一个.then,因为它只会跳过异步代码。

使用await/async时,你不再需要那么多箭头函数,这样你就可以像调试同步代码一样跳过await语句。

相关文章:

mac 制作usb启动盘_如何使用Mac制作Windows 10 USB-从Mac终端构建可启动的ISO

mac 制作usb启动盘Most new PCs dont come with DVD drives anymore. So it can be a pain to install Windows on a new computer.大多数新PC不再附带DVD驱动器。 因此,在新计算机上安装Windows可能会很痛苦。 Luckily, Microsoft makes a tool that you can use …

作业05-继承、多态、抽象类与接口

1. 本周学习总结 1.1 写出你认为本周学习中比较重要的知识点关键词 接口,Comparable,Comparator 1.2 尝试使用思维导图将这些关键词组织起来。 1.3 可选:使用常规方法总结其他上课内容。 1.接口特点:一个公开的界面 有统一定义的规…

炫彩流光按钮 html+css

话不多&#xff0c;先上效果&#xff1a; 简介&#xff1a; 用基础css做一个有一点炫酷的流光按钮&#xff0c;不止按钮&#xff0c;只要是盒子就行。 具体步骤&#xff1a; 1.先定义一个盒子当做按钮&#xff0c;如我就用a标签&#xff1a; <body><a href"#…

SQL取上一条, 下一条记录方法

如果我们需要取id为3的前后的1条记录. 就可以用以下方法 取上一条记录: select * from 表名 where id<3 order by id desc limit 1取下一条记录: select * from 表名 where id>3 order by id asc limit 1大小于比较 order limit 转载于:https://www.cnblogs.com/…

react中使用构建缓存_通过构建海滩度假胜地网站,了解如何使用React,Contentful和Netlify...

react中使用构建缓存In this full course from John Smilga you will learn React by building a beach resort website project. The project uses React router for routing, React context API for state management, Contentful headless CMS for data management, and Net…

R语言实战 - 基本统计分析(2)- 频数表和列联表

数据&#xff1a; > library(vcd) > head(Arthritis)ID Treatment Sex Age Improved 1 57 Treated Male 27 Some 2 46 Treated Male 29 None 3 77 Treated Male 30 None 4 17 Treated Male 32 Marked 5 36 Treated Male 46 Marked 6 23 …

随机位置显示图片不重叠前端实现详细讲解附效果图,代码可直接使用

目录先看看效果图所要实现的功能看看代码js代码讲解&#xff1a;下面看看完整代码吧小程序版本完整代码VUE版本的代码&#xff1a;先看看效果图 所要实现的功能 在页面上随机的位置显示随机大小的图片&#xff0c;并且每个图片不能重叠&#xff0c;完整实现代码。 看看代码 …

MVC缓存OutPutCache学习笔记 (一) 参数配置

OutPutCache 参数详解 Duration : 缓存时间&#xff0c;以秒为单位&#xff0c;这个除非你的LocationNone&#xff0c;可以不添加此属性&#xff0c;其余时候都是必须的。 Location : 缓存放置的位置; 该值为枚举值: None: 当被设置为None时&#xff0c;其余的任何设置将不起作…

在Mac上控制Alt Delete-如何在Macbook上打开任务管理器

It happens to the best of us: were working away on some important project, and our trusty computer freezes. Or rather, a program were in just stops responding. So what do you do?这对我们最好的人来说是偶然的&#xff1a;我们正在做一些重要的项目&#xff0c;而…

HEW MAP文件使用

参考资料转载于:https://www.cnblogs.com/iluzhiyong/p/5145396.html

算法导论九章 答案

http://blog.csdn.net/z84616995z/article/details/18840823?reload 9.3-8题&#xff1a; http://blog.csdn.net/z84616995z/article/details/18938181 9.3-9题&#xff1a; http://blog.csdn.net/z84616995z/article/details/18889535转载于:https://www.cnblogs.com/sa51718…

小程序实现瀑布流,获取图片高度分成两组数据的函数封装代码

把一个数组根据数组内部的图片的高度&#xff0c;拆分成两个数组&#xff0c;组成瀑布流数据的方法。 使用方式&#xff1a; async created() {var arr this.$mock.sssdata.data.lists;//arr 是一个数组&#xff0c;里面包含若干对象&#xff0c;对象里面有图片var myArr a…

实现线程哪种方法更好_实施数据以实现更好的用户体验设计的4种方法

实现线程哪种方法更好Gone are the days when design used to rely mainly on the color palettes and the creativity of the designer. In the rapidly expanding technological world of today, it is essential to work across departments to enhance the screen experien…

String比较.equals

首先定义四个变量str public class SIzhui {public static void main(String[] args) {String str1"wang";String str2"li";String str3"wang";String str4new String("wang");} } 然后进行比较 public class SIzhui {public static …

mac下mysql5.7.10密码问题

mysql5.7.10刚安装好&#xff0c;会生成一个随机密码。 如果没记住这个随机密码&#xff0c;那么到mysql/bin/下执行mysql_secure_installation命令 按照提示重置密码和其他选项。 ps&#xff1a;找了一下午终于找到方法了&#xff01;&#xff01;&#xff01; 转载于:https:/…

Error: Cannot find module ‘express‘

解决方案&#xff1a;把node_module整个文件夹删掉,然后npm clean cache,看下package.json里有没有express的依赖项,有的话直接npm install,没有的话 npm install express --save

Observables简介以及它们与Promise有何不同

‘Observables’, ‘Observables’, ‘Observables’...Yes! Today, we will talk about this often discussed word of the market. Well also learn how they are different from Promises (havent heard about Promises? Not to worry! You will know more soon). Let’s s…

Spring Boot项目错误:Error parsing lifecycle processing instructions

pom.xml文件错误&#xff1a;Error parsing lifecycle processing instructions 解决方法&#xff1a;清空.m2/repository下的所有依赖文件&#xff0c;重新下载即可解决该问题。转载于:https://www.cnblogs.com/EasonJim/p/7724683.html

oracle执行计划连接方式

嵌套循环&#xff08;Nested Loops &#xff08;NL&#xff09;&#xff09;假如有A、B两张表进行嵌套循环连接&#xff0c;那么Oracle会首先从A表中提取一条记录&#xff0c;然后去B表中查找相应的匹配记录&#xff0c;如果有的话&#xff0c;就把该条记录的信息推到等待返回的…

大转盘完整源码附效果图,可以下载直接用

本转盘实现功能&#xff0c;可以动态配置奖品和转盘相关的任何图片&#xff0c;可以灵活配置使用。是基于 uni-app 实现的。可以在小程序或者H5&#xff0c;各端兼容使用。 效果图&#xff1a;因为GIF图的掉帧&#xff0c;所以显示抽奖的转动速度慢&#xff0c;实际上转动比较…

使用FortJs使用现代JavaScript开发Node.js

介绍 (Introduction) Nodejs gives you the power to write server side code using JavaScript. In fact, it is very easy and fast to create a web server using Nodejs. There are several frameworks available on Node package manager which makes the development eve…

find 按时间查找

find 按时间查找 转载▼分类&#xff1a; linuxShell日记-mtime 修改时间-ctime 改变时间-atime 访问时间-mtime 5 至少5天之前修改过的文件&#xff0c;至少5天没修改过-mtime -5 5天之内修改过的文件-mtime 5 刚好5天前修改的文件 -perm 按权限查找 -perm 001 精确匹配权限…

转:从零开始做app需要做的事情列表

https://qdan.me/list/VaXl7N8emfv1ayWg 从零开始做App的Bootstrap 做一个App&#xff0c;需要很多东西。 不定期更新。 团队 工欲善其事&#xff0c;必先利其器。 需求管理 支持版本、迭代、需求的创建与管理。 产品经理在上面录入需求&#xff0c;开发参照开发&#xff0c;测…

uniapp自定义导航栏样式,自定义导航栏组件使用说明,兼容小程序和H5及各端

实现思路&#xff1a; 把底部导航做成一个组件&#xff0c;点击导航显示的页面也做成组件&#xff0c;在启动页面引入这四个组件&#xff0c;点击封装的导航组件就显示相应的组件页面&#xff0c;这样就不会出现页面重新加载的问题了&#xff0c;有个弊端就是导航页面不能使用…

javascript优化_如何通过使用服务人员来优化JavaScript应用

javascript优化Every now and then we hear about optimizing something. There are different kinds of optimizations we can do to make our apps faster and more efficient, or to save time or memory. This article will cover one of those methods — service worke…

【视觉SLAM14讲】ch3课后题答案

1.验证旋转矩阵是正交矩阵 感觉下面这篇博客写的不错 http://www.cnblogs.com/caster99/p/4703033.html 总结一下&#xff1a;旋转矩阵是一个完美的矩阵——正交矩阵。①行列式为1&#xff0c;②每个列向量都是单位向量且相互正交&#xff0c;③它的逆等于它的转置。 2.罗德里…

【转载】邻接表表示法

图的邻接表表示法 图的邻接表表示法类似于树的孩子链表表示法。对于图G中的每个顶点v i &#xff0c;该方法把所有邻接于v i 的顶点v j 链成一个带头 结点的单链表&#xff0c;这个单链表就称为顶点v i 的邻接表(Adjacency List)。 1&#xff0e; 邻接表的结点结构 &#xff08…

宝塔的服务忽然挂掉解决方法

先登录宝塔看内存是否满了 如果满了就点击文件&#xff0c;找到大文件进行删除&#xff0c;然后清空回收站&#xff0c;重启服务器&#xff0c;就解决了。 清空回收站&#xff1a;点击首页&#xff0c;打开终端&#xff0c;输入下面命令&#xff0c; 清空回收站的命令是&#…

免费创办网站_足够好的工程来创办一家互联网公司

免费创办网站I gave a guest lecture in an undergraduate software engineering class (CSCE431) at Texas A&M University in March 2019. Now I’ve turned this lecture into a blog post here, and hopefully some people on the Internet will find this useful.我于…

centos7下安装docker(11容器操作总结)

这段时间主要是学习了对容器的操作&#xff0c;包括&#xff1a;容器的状态&#xff1a;start&#xff0c;stop&#xff0c;restart&#xff0c;rename&#xff0c;pause&#xff0c;unpause&#xff0c;rm&#xff0c;attach&#xff0c;exec&#xff0c;kill&#xff0c;logs…