当前位置:网站首页>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 .
边栏推荐
猜你喜欢

MySql统计函数COUNT详解

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

裸金属云FASS高性能弹性块存储解决方案

我的理想工作,码农的绝对自由支配才是最重要的——未来创业的追求

Laravel service container (Application of context binding)

D3.JS 纵向关系图(加箭头,连接线文字描述)

Madonna "hellent" bought $1.3 million NFT boring ape, which is now considered too expensive

重庆大道云行作为软件产业代表受邀参加渝中区重点项目签约仪式

ASM插桩:学完ASM Tree api,再也不用怕hook了

The LAAS protocol of defi 2.0 is the key to revitalizing the development of defi track
随机推荐
Flink connector Oracle CDC 实时同步数据到MySQL(Oracle12c)
我的理想工作,码农的绝对自由支配才是最重要的——未来创业的追求
Show profiles of MySQL is used.
赓续新征程,共驭智存储
与张小姐的春夏秋冬(5)
nacos外置数据库的配置与使用
Fantom (FTM) prices will soar by 20% in the next few days
【数据库】数据库课程设计一一疫苗接种数据库
rsync+inotyfy实现数据单项监控实时同步
mysql在查询字符串类型的时候带单引号和不带的区别和原因
ASM插桩:学完ASM Tree api,再也不用怕hook了
华为2020校招笔试编程题 看这篇就够了(上)
超简单集成HMS ML Kit 人脸检测实现可爱贴纸
day02作业之进程管理
Use of xtrabackup
How does PHP generate QR code?
Under the bear market of encrypted assets, platofarm's strategy can still obtain stable income
SQL repair duplicate data
Rsync+inotyfy realize real-time synchronization of single data monitoring
IDEA中设置自动build-改动代码,不用重启工程,刷新页面即可