当前位置:网站首页>Promise learning notes
Promise learning notes
2022-07-28 09:16:00 【Peanut butter 12】
Promise Introduction and basic use
understand
Promise yes JS A new solution for asynchronous programming in ( The old scheme was to simply use callback functions )
Grammatically ,Promise It's a constructor
functionally ,Promise Object is used to encapsulate an asynchronous operation and obtain the result values of its success and failure
advantage
Specifying callback functions is more flexible
old : You must specify... Before starting an asynchronous task
promise: Start asynchronous task => return promise object => to promise Object binding callback function ( Even in asynchronous Specify multiple after the task ends )
Support chain calls , It can solve the problem of callback to hell
Back to hell : Callback function nested call , The result of the asynchronous execution of the external callback function is the condition of the nested callback execution
The drawback of callback hell : Not easy to read , Not convenient for exception handling
Solution :promise call chaining
promise The state of
Properties in object instances PromiseState
pending Undecided
resolved success
rejected Failure
Properties in object instances PromiseResult
Successfully saved the object / Results of failure
resolve The result data of success is generally called value
reject The result data of failure is generally called reason
Workflow

Promise API
1.Promise Constructors :Promise(executor){}
(1) executor function :(resolve,reject)=>{} actuator
(2) resolve function : Internally define the function to be called when successful value => {}
(3) reject function : The function called when the internal definition fails reason => {}
explain :executor Will be in Promise Internal immediate synchronization call , Asynchronous operations are performed in the actuator
2.Promise.prototype.then Method :(onResolved,onRejected)=>{}
(1)onResolved function : Successful callback function (value) => {}
(2)onRejected function : Failed callback function (reason) => {}
explain :resolve The function passes the successful value to onResolved function ,reject The function passes the successful value to onRejected function ,then Will return a new promise object
3.Promise.prototype.catch Method :(onRejected)=>{}
onRejected function : Failed callback function (reason) => {}
4.Promise.resolve Method :(value) => {}
value: Data or promise object
explain : Return a success / The failure of the promise object
value The value passed in is not Promise Object of type , The result returned is success promise object
PromiseState:fulfilled PromiseResult:value
value The parameter passed in is Promise object , Then the result of the parameter determines resolve Result
PromiseState:fulfilled PromiseResult:resolve Parameters of
PromiseState:rejected PromiseResult:rejected Parameters of
5.Promise.reject Method :(reason) => {}
reason: The reason for the failure
explain : Return to a failed promise object
PromiseState:rejected PromiseResult:reason
6.Promise.all Method :(promises) => {}
promises: contain n individual promise Array of
explain : Back to a new promise, Only all of promise Success is the only way to succeed , The result is all promise An array of results , As long as one fails, it will fail , The result is the first failure promise Result
6.Promise.race Method :(promises) => {}
promises: contain n individual promise Array of
explain : Back to a new promise, The first to finish promise The result state is the final result state
Promise key problem
change promise state
1. call resolve() pending => resolved
2. call reject() pending => rejected
3. Throw an error throw string pending => rejected
One promise More than one success was specified / Failed callback function , When promise It is called when it changes to the corresponding state
change promise Status and order of specifying callback functions
(1) It's possible , Normally, the callback is specified first and then the state is changed (resolve()/reject() Execute after asynchronous task execution )
(2) Change the status first, and then specify the callback
Call directly in the actuator resolve()/reject()
Call after a longer delay then()
(3) When to get the data
If it is the callback specified first , When the state changes , The callback function will call , Get data
If you change the state first , When specifying callback , The callback function will call , Get data
promise.then() Back to the new promise What determines the outcome status of
Put it simply : from then() The result of the specified callback function execution determines
Elaborate :
The callback function throws an error


The callback function returns Yes No Promise Object of type nothing retuun Then for defined

The callback function returns Promise Object of type

promise extraordinary transmission
(1) When using promise Of then Chain call , Failed callbacks can be specified at the end
(2) Any previous operation has an exception , Will be passed to the last failed callback for processing

interrupt promise chain
(1) When using promise Of then Chain call , Break in the middle , The subsequent callback function is no longer called
(2) Method : Returns a pendding State of promise object


Promise Custom encapsulation
async And await
async function
The return value of the function is promise object
promise The result value of the object is determined by async The return value of the function execution determines ( and then The result value of is the same )
await expression
await The expression on the right is usually promise object , But it can also be other values
If the expression is promise object ,await The return is promise The value of success
If the expression is another value , Take this value directly as await The return value of
Be careful
await Must be written in async Function , but async There can be no await
If await Of promise failed , Will throw an exception , Need to pass through try...catch Capture processing
边栏推荐
- Go interface Foundation
- Go panic and recover
- Detailed explanation of DHCP distribution address of routing / layer 3 switch [Huawei ENSP]
- TXT text file storage
- When I use MySQL CDC, there are 100 million pieces of data in the source table. In the full volume phase, when I synchronize 10 million, I stop, and then pass
- Bluetooth technology | it is reported that apple, meta and other manufacturers will promote new wearable devices, and Bluetooth will help the development of intelligent wearable devices
- Centralized log management with sentry
- Huid learning 7: Hudi and Flink integration
- Train your own classification [Bao Jiaobao, the data are ready]
- 实现批量数据增强 | keras ImageDataGenerator使用
猜你喜欢

【SwinTransformer源码阅读二】Window Attention和Shifted Window Attention部分

Learn to draw with nature communications -- complex violin drawing

opencv4.60版本安装和配置

You're not still using xshell, are you? This open source terminal tool is yyds!

Bluetooth technology | the total scale of charging piles in Beijing will reach 700000 in 2025. Talk about the indissoluble relationship between Bluetooth and charging piles

Path and attribute labels of picture labels

从开发转测试:我从零开始,一干就是6年的自动化测试历程

Starfish Os打造的元宇宙生态,跟MetaBell的合作只是开始

Huid learning 7: Hudi and Flink integration

mysql主从架构 ,主库挂掉重启后,从库怎么自动连接主库
随机推荐
A new method of exposing services in kubernetes clusters
Principle of line of sight tracking and explanation of the paper
Hyperlink label
Mysql5.7.38 start keepalived in the container
蓝牙技术|2025年北京充电桩总规模达70万个,聊聊蓝牙与充电桩的不解之缘
NPM and yarn use (official website, installation, command line, uploading your own package, detailed explanation of package version number, updating and uninstalling package, viewing all versions, equ
ES6 let and Const
C simply call FMU for simulation calculation
XMIND Zen installation tutorial
Go synergy
Argocd Web UI loading is slow? A trick to teach you to solve
Why setting application.targetframerate doesn't work
Go interface Foundation
Learn to draw with nature communications -- complex violin drawing
Introduction of functions in C language (blood Book 20000 words!!!)
mysql主从架构 ,主库挂掉重启后,从库怎么自动连接主库
剑指offer
ES6 变量的解构赋值
2022年危险化学品经营单位安全管理人员上岗证题目及答案
Path and attribute labels of picture labels