当前位置:网站首页>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()
边栏推荐
- 【数据库 三大范式】一看就懂
- MySQL锁总结(全面简洁 + 图文详解)
- 这次,彻底搞清楚MySQL索引
- 记一次猫舍由外到内的渗透撞库操作提取-flag
- 【九阳神功】2021复旦大学应用统计真题+解析
- 5月14日杂谈
- [graduation season · advanced technology Er] goodbye, my student days
- 3.输入和输出函数(printf、scanf、getchar和putchar)
- Nuxtjs快速上手(Nuxt2)
- About the parental delegation mechanism and the process of class loading
猜你喜欢
Differences among fianl, finally, and finalize
4. Branch statements and loop statements
. Net6: develop modern 3D industrial software based on WPF (2)
2022泰迪杯数据挖掘挑战赛C题思路及赛后总结
C语言入门指南
[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
Cookie和Session的区别
撲克牌遊戲程序——人機對抗
A piece of music composed by buzzer (Chengdu)
canvas基础2 - arc - 画弧线
随机推荐
【九阳神功】2022复旦大学应用统计真题+解析
9. Pointer (upper)
The difference between cookies and sessions
Mortal immortal cultivation pointer-1
杂谈0516
Floating point comparison, CMP, tabulation ideas
实验七 常用类的使用
[中国近代史] 第九章测验
PriorityQueue (large root heap / small root heap /topk problem)
自定义RPC项目——常见问题及详解(注册中心)
重载和重写的区别
使用Spacedesk实现局域网内任意设备作为电脑拓展屏
5. Function recursion exercise
7-4 散列表查找(PTA程序设计)
仿牛客技术博客项目常见问题及解答(二)
(原创)制作一个采用 LCD1602 显示的电子钟,在 LCD 上显示当前的时间。显示格式为“时时:分分:秒秒”。设有 4 个功能键k1~k4,功能如下:(1)k1——进入时间修改。
3. Number guessing game
Wechat applet
[hand tearing code] single case mode and producer / consumer mode
【数据库 三大范式】一看就懂