当前位置:网站首页>The difference between asyncawait and promise
The difference between asyncawait and promise
2022-07-29 05:58:00 【Benben's coriander】
async
async Function definition
async Functions are functions declared with keywords .async yes “ asynchronous ” Abbreviation , So it should be easy to understand async Used to state a function It's asynchronous .
effect
For resolution : Generated by asynchronous program bug
####async Syntax of functions
async function name([param[, param[, ... param]]]) {
statements
}
Parameters :name The name of the function
param The name of the parameter to be passed to the function
statements An expression that contains the body of a function , have access to await
Return value : A brand new promise, This promise Or it will pass a test by async The value returned by the function is resolved , Or it will pass through a from async Thrown in a function ( Or not captured in it ) Exception rejected
The following is async The concrete use example of :
async function foo(p) {
console.log("foo run",p);
return 1;
}
var res = foo(1);
console.log(res);//{<fulfilled>: 1}
async Function must return a promise object . If one async The return value of the function does not appear to be promise, Then it will be implicitly packaged in a promise in .
for example , The following code :
async function foo() {
//promise.[[promiseValue]]
return 1
}
// Equivalent to
function foo() {
return Promise.resolve(1)
}//{<fulfilled>: 1}
The following is true. async Some supplements to :
async Itself is a grammar sugar —> Grammatical sugar : Keywords with certain functions
- Grammatical sugar The role of : can Reduce the amount of code 、 Increase the readability of the program , So as to reduce the chance of program code error
async Function return How to accept
Mode one
adopt promise.then-cb Formal parameter acquisition
async function foo(){
console.log(222222);
return 123;
}
let res = foo();
res.then(data=>{
console.log(data);//123
})
Mode two
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 await
let res = await foo();
console.log(res);
})()
async function foo(){
console.log('foo run');
return 123;
}
//res effect : Accept async foo Function return value yes promise
let res = foo();
await
await Definition
await It means waiting , So it should be easy to understand ,await Wait for an operation to complete .
effect
await The role of keywords Just get take Promise Content returned in , What you get is Promise Function resolve perhaps reject Value (await The function is to get promise.[[promiseValue]] Value )
About await Points for attention
await Must be written in async in
await And then there's a promise Instance object
[[promiseValue]]
[[PromiseValue]] Is an internal variable , There is no outside access to , Only in then In order to get .
[promiseValue] Which can be assigned
- async Functional return
- new promise in resolve Actual parameters
- then in return (catch finally Medium return)
- promise.reslove() Actual parameters promise.reject() Actual parameters
Differences among the three
- promise and async/await Are a way to solve asynchronous programming , however async/await Make asynchronous code look like synchronous code .
- There is one more in front of the function async keyword .await Keywords can only be used for async Within the function defined .async The function returns one implicitly Promise, The promise Of resolve The value is return Value .
Why? async/await Better ?
Use async Functions can make code much simpler , No need to be like Promise Just as much then, There is no need to write anonymous functions to handle Promise Of resolve Value , There's no need to define redundant data Variable , It also avoids nested code .
async/await Give Way try/catch Can handle synchronous and asynchronous errors at the same time . In the following example ,try/catch Can't handle JSON.parse Error of , Because it is in Promise in , We need to use .catch, Such errors will make the code very redundant .
边栏推荐
- 中海油集团,桌面云&网盘存储系统应用案例
- Fantom (FTM) prices will soar by 20% in the next few days
- 并发编程学习笔记 之 原子操作类AtomicInteger详解
- “山东大学移动互联网开发技术教学网站建设”项目实训日志五
- Training log 7 of the project "construction of Shandong University mobile Internet development technology teaching website"
- Shanzhai coin Shib has a US $548.6 million stake in eth whale's portfolio - traders should be on guard
- 剑指核心-TaoCloud全闪SDS助力构建高性能云服务
- 并发编程学习笔记 之 原子操作类AtomicReference、AtomicStampedReference详解
- File文件上传的使用(2)--上传到阿里云Oss文件服务器
- 突破硬件瓶颈(一):Intel体系架构的发展与瓶颈挖掘
猜你喜欢

Breaking through the hardware bottleneck (I): the development of Intel Architecture and bottleneck mining

Flutter正在被悄悄放弃?浅析Flutter的未来

微信小程序源码获取(附工具的下载)

“山东大学移动互联网开发技术教学网站建设”项目实训日志七

Refresh, swagger UI theme changes

mysql 的show profiles 使用。

突破硬件瓶颈(一):Intel体系架构的发展与瓶颈挖掘

mysql插入百万数据(使用函数和存储过程)

July 28 ens/usd Value Forecast: ENS attracts huge profits

Tear the ORM framework by hand (generic + annotation + reflection)
随机推荐
Elastic box flex
“山东大学移动互联网开发技术教学网站建设”项目实训日志一
ssm整合
Basic use of array -- traverse the circular array to find the maximum value, minimum value, maximum subscript and minimum subscript of the array
Flink connector Oracle CDC 实时同步数据到MySQL(Oracle19c)
剑指核心-TaoCloud全闪SDS助力构建高性能云服务
Rsync+inotyfy realize real-time synchronization of single data monitoring
并发编程学习笔记 之 ReentrantLock实现原理的探究
mysql 的show profiles 使用。
与张小姐的春夏秋冬(2)
XDFS&空天院HPC集群典型案例
Dao race track is booming. What are the advantages of m-dao?
day02 作业之文件权限
Detailed explanation of atomic operation class atomicinteger in learning notes of concurrent programming
Laravel service container (Application of context binding)
30 knowledge points that must be mastered in quantitative development [what is level-2 data]
Thinkphp6 output QR code image format to solve the conflict with debug
CMD window under Windows connects to MySQL and operates the table
nacos外置数据库的配置与使用
并发编程学习笔记 之 工具类Semaphore(信号量)