当前位置:网站首页>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
PromiseIs a solution to asynchronous programming : Grammatically speaking ,promiseIt'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 timePromiseIt can ensure that asynchronous requests become executed sequentiallyConcept :
PromiseyesES6New grammar in , Itself a constructor ; EverynewComing outPromiseInstance 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
})
PromiseIt's a constructor , SurenewAn object , Itself is an asynchronous operationPromiseOfthenMethodPromiseThere are two method parameters when usingsuccessCb,errorCbRespectively represents the success or failure of executionPromiseObjects can pass throughthenMethod pairsuccessCbanderrorCbTo 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
ES7MediumasyncandawaitCan be simplifiedPromisecall , ImprovePromiseCode reading and understandingasyncandawaitCombine , It can make the asynchronous call not returnPromise, And just putthenParameters of parameter method ( It's alsosuccessCbfunction arguments ) Come back , Make code more frugal , Improve code development efficiency , It can also ensure the sequential execution of asynchronous callsasync、awaitVarious use cases :
Be careful :
asyncandawaitMust appear at the same time
OneasyncCan correspond to multipleawaitawaitThe result of modification must bePromiseobject
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 callbackssuccessCbanderrorCbParameters- These two callbacks can be through
thenandcatch()Receive , But the asynchronous calling code is more or less reflected in the degree of hell callback asyncandawaitcombination , The return ofPromiseDirectly intosuccessCbArguments of , Greatly simplifies the complexity of code development , Improve development efficiency- If necessary , adopt
try/catchcaptureasyncandawait - Usually use ,
async、await、abnormalThe 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()
边栏推荐
- Redis实现分布式锁原理详解
- Implementation principle of automatic capacity expansion mechanism of ArrayList
- 【九阳神功】2022复旦大学应用统计真题+解析
- Miscellaneous talk on May 14
- 自定义RPC项目——常见问题及详解(注册中心)
- [面試時]——我如何講清楚TCP實現可靠傳輸的機制
- Read only error handling
- 简述xhr -xhr的基本使用
- Redis cache obsolescence strategy
- [the Nine Yang Manual] 2020 Fudan University Applied Statistics real problem + analysis
猜你喜欢

Caching mechanism of leveldb

C语言入门指南

强化学习系列(一):基本原理和概念

Principles, advantages and disadvantages of two persistence mechanisms RDB and AOF of redis

MySQL锁总结(全面简洁 + 图文详解)

撲克牌遊戲程序——人機對抗

3. C language uses algebraic cofactor to calculate determinant

(原创)制作一个采用 LCD1602 显示的电子钟,在 LCD 上显示当前的时间。显示格式为“时时:分分:秒秒”。设有 4 个功能键k1~k4,功能如下:(1)k1——进入时间修改。

1. C language matrix addition and subtraction method

透彻理解LRU算法——详解力扣146题及Redis中LRU缓存淘汰
随机推荐
C language Getting Started Guide
C语言入门指南
【九阳神功】2016复旦大学应用统计真题+解析
QT meta object qmetaobject indexofslot and other functions to obtain class methods attention
编写程序,模拟现实生活中的交通信号灯。
FAQs and answers to the imitation Niuke technology blog project (II)
【九阳神功】2018复旦大学应用统计真题+解析
[graduation season · advanced technology Er] goodbye, my student days
实验四 数组
仿牛客技术博客项目常见问题及解答(三)
1. C language matrix addition and subtraction method
About the parental delegation mechanism and the process of class loading
. Net6: develop modern 3D industrial software based on WPF (2)
Why use redis
一段用蜂鸣器编的音乐(成都)
Zatan 0516
[中国近代史] 第九章测验
Inaki Ading
Safe driving skills on ice and snow roads
This time, thoroughly understand the MySQL index