当前位置:网站首页>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 .
边栏推荐
- DCAT batch operation popup and parameter transfer
- MySql统计函数COUNT详解
- Research and implementation of flash loan DAPP
- 我的理想工作,码农的绝对自由支配才是最重要的——未来创业的追求
- Breaking through the hardware bottleneck (I): the development of Intel Architecture and bottleneck mining
- Thinkphp6 output QR code image format to solve the conflict with debug
- 识变!应变!求变!
- mysql在查询字符串类型的时候带单引号和不带的区别和原因
- Win10+opencv3.2+vs2015 configuration
- 全闪分布式,如何深度性能POC?
猜你喜欢

Plato farm is expected to further expand its ecosystem through elephant swap

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

datax安装

Process management of day02 operation

Read and understand move2earn project - move

Tear the ORM framework by hand (generic + annotation + reflection)

CMD window under Windows connects to MySQL and operates the table

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

SSM integration

ASM插桩:学完ASM Tree api,再也不用怕hook了
随机推荐
Elastic box flex
Novice introduction: download from PHP environment to thinkphp6 framework by hand
“山东大学移动互联网开发技术教学网站建设”项目实训日志一
超简单集成HMS ML Kit 人脸检测实现可爱贴纸
iSCSI vs iSER vs NVMe-TCP vs NVMe-RDMA
CMD window under Windows connects to MySQL and operates the table
深度学习的趣味app简单优化(适合新手)
Use of xtrabackup
Bare metal cloud FASS high performance elastic block storage solution
DataX installation
Windos下安装pyspider报错:Please specify --curl-dir=/path/to/built/libcurl解决办法
day02作业之进程管理
Huawei 2020 school recruitment written test programming questions read this article is enough (Part 1)
Detailed explanation of atomic operation classes atomicreference and atomicstampedreference in learning notes of concurrent programming
并发编程学习笔记 之 原子操作类AtomicInteger详解
Refresh, swagger UI theme changes
Nailing alarm script
Super simple integration of HMS ml kit to realize parent control
以‘智’提‘质|金融影像平台解决方案
isAccessible()方法:使用反射技巧让你的性能提升数倍