当前位置:网站首页>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()
边栏推荐
- Difference and understanding between detected and non detected anomalies
- 【九阳神功】2017复旦大学应用统计真题+解析
- hashCode()与equals()之间的关系
- SRC挖掘思路及方法
- 7-14 错误票据(PTA程序设计)
- [the Nine Yang Manual] 2019 Fudan University Applied Statistics real problem + analysis
- 【VMware异常问题】问题分析&解决办法
- 2. First knowledge of C language (2)
- 重载和重写的区别
- [graduation season · advanced technology Er] goodbye, my student days
猜你喜欢
Read only error handling
It's never too late to start. The tramp transformation programmer has an annual salary of more than 700000 yuan
5. Function recursion exercise
Wei Pai: the product is applauded, but why is the sales volume still frustrated
6. Function recursion
仿牛客技术博客项目常见问题及解答(三)
4. Branch statements and loop statements
Reinforcement learning series (I): basic principles and concepts
(原创)制作一个采用 LCD1602 显示的电子钟,在 LCD 上显示当前的时间。显示格式为“时时:分分:秒秒”。设有 4 个功能键k1~k4,功能如下:(1)k1——进入时间修改。
ABA问题遇到过吗,详细说以下,如何避免ABA问题
随机推荐
Redis实现分布式锁原理详解
5月14日杂谈
[the Nine Yang Manual] 2018 Fudan University Applied Statistics real problem + analysis
Nuxtjs快速上手(Nuxt2)
Implementation principle of automatic capacity expansion mechanism of ArrayList
撲克牌遊戲程序——人機對抗
[modern Chinese history] Chapter 6 test
A piece of music composed by buzzer (Chengdu)
.Xmind文件如何上传金山文档共享在线编辑?
About the parental delegation mechanism and the process of class loading
【数据库 三大范式】一看就懂
Difference and understanding between detected and non detected anomalies
5. Function recursion exercise
TypeScript快速入门
附加简化版示例数据库到SqlServer数据库实例中
1.C语言初阶练习题(1)
String abc = new String(“abc“),到底创建了几个对象
(original) make an electronic clock with LCD1602 display to display the current time on the LCD. The display format is "hour: minute: Second: second". There are four function keys K1 ~ K4, and the fun
Using qcommonstyle to draw custom form parts
简单理解ES6的Promise