当前位置:网站首页>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 .
边栏推荐
- Idea using JDBC to connect mysql database personal detailed tutorial
- Breaking through the hardware bottleneck (I): the development of Intel Architecture and bottleneck mining
- Move protocol global health declaration, carry out the health campaign to the end
- 华为2020校招笔试编程题 看这篇就够了(上)
- 与张小姐的春夏秋冬(3)
- 并发编程学习笔记 之 Lock锁及其实现类ReentrantLock、ReentrantReadWriteLock和StampedLock的基本用法
- Refresh, swagger UI theme changes
- Tear the ORM framework by hand (generic + annotation + reflection)
- 超简单集成HMS ML Kit 人脸检测实现可爱贴纸
- Shanzhai coin Shib has a US $548.6 million stake in eth whale's portfolio - traders should be on guard
猜你喜欢

Gluster集群管理小分析

yum本地源制作

全闪分布式,如何深度性能POC?

如何零代码制作深度学习的趣味app(适合新手)

Laravel swagger add access password

Flutter 绘制技巧探索:一起画箭头(技巧拓展)

"Shandong University mobile Internet development technology teaching website construction" project training log I

ReportingService WebService Form身份验证

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

XDFS&中国日报社在线协同编辑平台典型案例
随机推荐
iSCSI vs iSER vs NVMe-TCP vs NVMe-RDMA
Training log III of "Shandong University mobile Internet development technology teaching website construction" project
闪贷Dapp的调研及实现
PHP write a diaper to buy the lowest price in the whole network
Intelligent security of the fifth space ⼤ real competition problem ----------- PNG diagram ⽚ converter
Centos7 silently installs Oracle
学习、研究编程之道
The Platonic metauniverse advocated by musk has long been verified by platofarm
Training log 4 of the project "construction of Shandong University mobile Internet development technology teaching website"
Show profiles of MySQL is used.
xSAN高可用—XDFS与SAN融合焕发新生命力
并发编程学习笔记 之 工具类Semaphore(信号量)
Use of xtrabackup
30 knowledge points that must be mastered in quantitative development [what is individual data]?
Okaleido tiger logged into binance NFT on July 27, and has achieved good results in the first round
Process management of day02 operation
Training log II of the project "construction of Shandong University mobile Internet development technology teaching website"
IDEA中设置自动build-改动代码,不用重启工程,刷新页面即可
在uni-app项目中,如何实现微信小程序openid的获取
Breaking through the hardware bottleneck (I): the development of Intel Architecture and bottleneck mining