当前位置:网站首页>Simply understand the promise of ES6
Simply understand the promise of ES6
2022-07-06 13:50:00 【Ling Xiaoding】
Simple understanding ES6 Of Promise
List of articles
Preface
Promise
Is a solution to asynchronous programming : Grammatically speaking ,promise
It's an object , From it you can get messages for asynchronous operations ; From the original point of view , It's a promise , Promise that it will give you a result after a period of timePromise
It can ensure that asynchronous requests become executed sequentiallyConcept :
Promise
yesES6
New grammar in , Itself a constructor ; Everynew
Coming outPromise
Instance object , Both represent an asynchronous operationeffect : Solved the problem of callback hell ( That is, asynchronous nested calls )
Back to hell : Refers to the callback function , The code form of nested callback function ; If the nesting level is very deep , It's hell ;
Callback hell is not conducive to code reading 、 Maintenance and later expansion
Promise How to use it?
- Create specific asynchronous operation objects
const p = new Promise(function(successCb, errorCb){
// In this function Define specific asynchronous operations in
// successCb Successful callback
// errorCb Failed callback
})
Promise
It's a constructor , Surenew
An object , Itself is an asynchronous operationPromise
Ofthen
MethodPromise
There are two method parameters when usingsuccessCb
,errorCb
Respectively represents the success or failure of executionPromise
Objects can pass throughthen
Method pairsuccessCb
anderrorCb
To call
There are two specific situations as follows :
result.then(function(data){
/* Successful callback */},function(data){
/* Failed callback */})
result.then(function(){
/* Successful callback */}).catch(function(data){
/* Failed callback */})
In the former then
Method accepts successCb
and errorCb
Callback function
The latter passes then
and catch
The two methods accept successCb
and errorCb
Callback function
- example :
// introduce fs modular
const fs = require('fs')
// 4) Promise Intervene and enrich the operation ( Join the success 、 Failed callback )
function getFileCont(filename) {
// Instantiation Promise object , Used to indicate asynchronous operation
// new Promise(function(successCb function , errorCb function ){})
// successCb: The current asynchronous operation is ok In this case, the execution is triggered resolve
// errorCb: An error occurred in the current asynchronous operation ( exceeding one's expectations ) Next trigger execution reject
return new Promise(function(successCb, errorCb) {
// Embody asynchronous process
fs.readFile(filename, 'utf8', function(err, data) {
if (err) {
return errorCb(' An error occurred while reading the file :' + err)
}
// All operations are ok Normal handling in case , Give the processed results to resolve call ( return )
successCb(data)
})
})
}
// The following can guarantee In order Get the results
getFileCont('./files/1.txt').then(function(result) {
console.log(result)
return getFileCont('./files/2.txt')
}).then(function(result){
console.log(result)
return getFileCont('./files/3.txt')
}).then(function(result){
console.log(result)
}).catch(function(err){
console.log(err)
})
ES7 Of async and await
ES7
Mediumasync
andawait
Can be simplifiedPromise
call , ImprovePromise
Code reading and understandingasync
andawait
Combine , It can make the asynchronous call not returnPromise
, And just putthen
Parameters of parameter method ( It's alsosuccessCb
function arguments ) Come back , Make code more frugal , Improve code development efficiency , It can also ensure the sequential execution of asynchronous callsasync
、await
Various use cases :
Be careful :
async
andawait
Must appear at the same time
Oneasync
Can correspond to multipleawait
await
The result of modification must bePromise
object
var obj = {
async getInfo(){
await getXXXX()
await getXXXX()
}
}
or
function ffff(){
// async It needs to be set to Promise The nearest outer layer of the object function In front of
getInfo(async function(){
await getXXXX()
//console.log(getXXXX())
})
}
or
async function XXXX(){
await getXXXX()
}
summary
new Promise()
Instantiate objects , The parameter callback function will have two callbackssuccessCb
anderrorCb
Parameters- These two callbacks can be through
then
andcatch()
Receive , But the asynchronous calling code is more or less reflected in the degree of hell callback async
andawait
combination , The return ofPromise
Directly intosuccessCb
Arguments of , Greatly simplifies the complexity of code development , Improve development efficiency- If necessary , adopt
try/catch
captureasync
andawait
- Usually use ,
async
、await
、abnormal
The solution of asynchronous sequential execution provided by the combination of three technologies
async function getThreeFile(){
try{
console.log(await getFileCont('./files/1.txt'))
console.log(await getFileCont('./files/2.txt'))
console.log(await getFileCont('./files/3.txt'))
}catch(err){
console.log(err)
}
}
getThreeFile()
边栏推荐
- A comprehensive summary of MySQL transactions and implementation principles, and no longer have to worry about interviews
- 6. Function recursion
- 实验八 异常处理
- Service ability of Hongmeng harmonyos learning notes to realize cross end communication
- C language to achieve mine sweeping game (full version)
- [面试时]——我如何讲清楚TCP实现可靠传输的机制
- 仿牛客技术博客项目常见问题及解答(三)
- Zatan 0516
- It's never too late to start. The tramp transformation programmer has an annual salary of more than 700000 yuan
- 【黑马早报】上海市监局回应钟薛高烧不化;麦趣尔承认两批次纯牛奶不合格;微信内测一个手机可注册俩号;度小满回应存款变理财产品...
猜你喜欢
Principles, advantages and disadvantages of two persistence mechanisms RDB and AOF of redis
PriorityQueue (large root heap / small root heap /topk problem)
7-5 走楼梯升级版(PTA程序设计)
编写程序,模拟现实生活中的交通信号灯。
The latest tank battle 2022 full development notes-1
6. Function recursion
甲、乙机之间采用方式 1 双向串行通信,具体要求如下: (1)甲机的 k1 按键可通过串行口控制乙机的 LEDI 点亮、LED2 灭,甲机的 k2 按键控制 乙机的 LED1
Difference and understanding between detected and non detected anomalies
FAQs and answers to the imitation Niuke technology blog project (II)
2. C language matrix multiplication
随机推荐
Cookie和Session的区别
简述xhr -xhr的基本使用
FAQs and answers to the imitation Niuke technology blog project (II)
7-9 制作门牌号3.0(PTA程序设计)
8. C language - bit operator and displacement operator
Caching mechanism of leveldb
MySQL中count(*)的实现方式
5月14日杂谈
7. Relationship between array, pointer and array
[dark horse morning post] Shanghai Municipal Bureau of supervision responded that Zhong Xue had a high fever and did not melt; Michael admitted that two batches of pure milk were unqualified; Wechat i
.Xmind文件如何上传金山文档共享在线编辑?
【数据库 三大范式】一看就懂
FAQs and answers to the imitation Niuke technology blog project (III)
4. Binary search
Custom RPC project - frequently asked questions and explanations (Registration Center)
[中国近代史] 第五章测验
Beautified table style
甲、乙机之间采用方式 1 双向串行通信,具体要求如下: (1)甲机的 k1 按键可通过串行口控制乙机的 LEDI 点亮、LED2 灭,甲机的 k2 按键控制 乙机的 LED1
透彻理解LRU算法——详解力扣146题及Redis中LRU缓存淘汰
Difference and understanding between detected and non detected anomalies