当前位置:网站首页>The difference between asyncawait and promise
The difference between asyncawait and promise
2022-07-30 05:55:00 【good moon births autumn】
async
async function definition
Async functions are functions declared using the keyword.async is short for "asynchronous", so it should be well understood that async is used to declare that a function is asynchronous.
Function
Used to solve: bugs generated by asynchronous programs
####async function syntax
async function name([param[, param[, ... param]]]) {statements}Parameter: name function name
param The name of the parameter to pass to the function
statements contains the expression of the function body, you can use await
Return value: A brand new promise that will either be resolved with a value returned by the async function, or rejected with an exception thrown (or uncaught) from the async function
The following is a specific use case of async:
async function foo(p) {console.log("foo run",p);return 1;}var res = foo(1);console.log(res);//{: 1} Async functions must return a promise object.If the return value of an async function does not appear to be a promise, then it will be implicitly wrapped in a promise.
For example, the following code:
async function foo() {//promise.[[promiseValue]]return 1}//Equivalent tofunction foo() {return Promise.resolve(1)}//{: 1} Here are some additions to async:
async itself is a syntactic sugar—>Syntax sugar: keywords with certain functions
- Syntax sugar The role of a>: It can reduce the amount of code and increase the readability of the program, thereby reducing the chance of program code errors
How to accept return value in async function
Method One
Get through promise.then-cb parameter
async function foo(){console.log(222222);return 123;}let res = foo();res.then(data=>{console.log(data);//123})Method 2
The second way to accept the return value of a function is await
(async function (){console.log('async run');//The second way to accept the return value of a function is awaitlet res = await foo();console.log(res);})()async function foo(){console.log('foo run');return 123;}//res role: accept the return value of async foo function is promiselet res = foo();await
await definition
await means to wait, so it should be well understood that await waits for an operation to complete.
Function
The function of the await keyword is to get the content returned in the Promise, and get the value of resolve or reject in the Promise function (the function of await is to get the value of promise.[[promiseValue]])
Notes about await
await must be written in async
await is followed by a promise instance object
[[promiseValue]]
[[PromiseValue]] is an internal variable, which cannot be obtained externally, but can only be obtained in then.
[promiseValue]Which can be assigned
- return of async function
- Resolve arguments in new promise
- return in then (return in catch finally)
- promise.reslove() argument promise.reject() argument
The difference between the three
- Promises and async/await are both ways of solving asynchronous programming, but async/await makes asynchronous code look like synchronous code.
- There is an async keyword in front of the function.The await keyword can only be used inside async functions.The async function implicitly returns a Promise, and the resolve value of the promise is the return value.
Why async/await is better?
Using the async function can make the code much simpler, it doesn't need then like Promise, no need to write anonymous function to deal with the value of Promise's resolve, no need to define redundant data variables, and nested code is avoided.
async/await allows try/catch to handle both synchronous and asynchronous errors.In the example below, try/catch can't handle JSON.parse errors, because it's in Promise, we need to use .catch, such errors will make the code very redundant.
Let me introduce myself first. The editor graduated from Shanghai Jiaotong University in 2013. I worked in a small company and went to big factories such as Huawei and OPPO. I joined Alibaba in 2018, until now.I know that most junior and intermediate java engineers want to upgrade their skills, they often need to explore their own growth or sign up to study, but for training institutions, the tuition fee is nearly 10,000 yuan, which is really stressful.Self-learning that is not systematic is very inefficient and lengthy, and it is easy to hit the ceiling and the technology stops.Therefore, I collected a "full set of learning materials for java development" for everyone. The original intention is very simple. I hope to help friends who want to learn by themselves but don't know where to start, and at the same time reduce everyone's burden.Add the business card below to get a full set of learning materials
边栏推荐
猜你喜欢

The use of Conluce, an online document management system

即刻报名|前沿技术探索:如何让 Spark 更强劲、更灵活

Path dependence: the poor hard science to counter attack breakthrough

给小白的 PostgreSQL 容器化部署教程(上)

2022年SQL大厂高频实战面试题(详细解析)

2022 Pengcheng Cup web

Different lower_case_table_names settings for server (‘1‘) and data dictionary (‘0‘) 解决方案

从字节码角度带你彻底理解i++与++i

上交所行情文件解析之mktdt04
![[Redis Master Cultivation Road] Jedis - the basic use of Jedis](/img/e3/0c6efd03432a01f857796f0bf648ef.png)
[Redis Master Cultivation Road] Jedis - the basic use of Jedis
随机推荐
解决没有配置本地nacos但是一直发生localhost8848连接异常的问题
【图像处理】基于中轴变换实现图像骨架提取附matlab代码
JVM 类加载机制 超详细学习笔记(三)
剑指offer(刷题篇12)
解读 Kylin 3.0.0 | 更敏捷、更高效的 OLAP 引擎
postman 请求 post 调用 传 复合 json数据
倒计数(来源:Google Kickstart2020 Round C Problem A)(DAY 88)
排列数字(DAY90)dfs
An old programmer's summary review of 2020, how to become more awesome in 2021
idea设置自动带参数的方法注释(有效)
RadonDB PostgreSQL on K8s 2.1.0 发布!
[Mysql] CONVERT函数
JVM 内存结构 超详细学习笔记(一)
Programmers care guide, give yourself a chance to make the occasional relaxation of body and mind
力扣05-替换空格——字符串问题
839. 模拟堆
Participate in open source, let programmers regain their blood and passion
MySQL kills 10 questions, how many questions can you stick to?
leetcode hot 100(刷题篇11)(231/235/237/238/292/557/240/36)offer/3/4/5
为Bitbucket 和 Sourcetree 设置SSL认证