当前位置:网站首页>Es6.--promise, task queue and event cycle
Es6.--promise, task queue and event cycle
2022-07-28 02:58:00 【Like to drink pearl milk tea】
Tips : When the article is finished , Directories can be generated automatically , How to generate it, please refer to the help document on the right
List of articles
Catalog
(1) Sync 、 Asynchronous design idea
Asynchronous design idea - Callback function
2. Task queues and event loops
1.promise summary
(1)promise yes Asynchronous programming A solution for . grammatically ,Promise It's an object , From it can Get asynchronous operation The news of .
(2)Promise There are three states of asynchronous operation :pending( Have in hand )、fulfilled( Have succeeded ) and rejected( Failed ). Except for the results of asynchronous operations , No other operation can change this state .
(3)Promise The only object is : from pending Turn into fulfilled And from the pending Turn into rejected The state of change . As long as in fulfilled and rejected , The state will not change again, that is resolved( Have to finalize the design ).
(4)Promise It's a constructor , The prototype has then、catch Method , There are reject、resolve Method .
(1) Sync 、 Asynchronous design idea
Sync 、 The concept of asynchrony
Sync : In a certain order , After executing one, you can execute the next
asynchronous : The order of execution is uncertain , Determined by trigger conditions , When to execute is also uncertain , Even timers ( Let's explain ), Asynchronous processing can execute multiple at the same time .
Synchronous design idea
function createData(){ return parseInt((Math.random()*(90-50)+50)) } var obj={ data:100, tool:function(){ var data=createData() this.data=data } } obj.tool() console.log(obj.data)Running results :
Asynchronous design idea - Callback function
function createData(callback) { callback(parseInt((Math.random() * (90 - 50) + 50))) } var obj = { data: 100, tool: function() { var a = 20; createData((n) => { this.data = n }) var b=100; for(;;){} } } obj.tool() console.log(obj.data)
function fn (cb,n) { for(var i=0;i<n;i++){} cb() } // An asynchronous function console.log(1) fn(function(){console.log(3)},10000) // There is also a print function inside this function 3 console.log(5) // fn A function cannot be asynchronous however js The bottom of the c/c++ There are asynchronous functions that do not block code setTimeout(function(){console.log(4)},1000) console.log(2)
function fn (cb,n) { for(var i=0;i<n;i++){} cb() } // An asynchronous function console.log(1) fn(function(){console.log(3)},10000) //fn Blocking , After executing first, execute output 5 console.log(5) // fn A function cannot be asynchronous however js The bottom of the c/c++ There are asynchronous functions that do not block code setTimeout(function(){console.log(4)},1000) console.log(2) //fn It's delayed , So print first 2 In the printout 4
Running results :

(2) Blocking asynchrony
Examples of blocking asynchrony :
// Blocking asynchrony
fn1(function(){console.log(1)})
// Official non blocking asynchronous functions
setTimeOut(function(){console.log(2)})
// Blocking asynchrony
fn3(function(){console.log(3)})
(3)promise grammar
setTimeout() Function is a non blocking asynchronous function
setTimeout(()=>{console.log(11)},3000)
setTimeout(()=>{console.log(22)},4000)
Back end fs.readFile() function Also a Non blocking asynchronous functions
es6 Medium promise Object's then function Also a Non blocking asynchronous functions
1.Promise It's a ES5 There it is ES6 Write the standard directly
2.Promise It's a constructor Created a data container
Data container :map set arr object, They are passively generating data Add data to it
Promise Actively generate data Don't add data to it It generates data by itself
for example :
var p1=new Promise(function(n1,n2){ var n=Math.random() n1(n) //n1 Called On behalf of p1 Generated data })Running results :
(4)then() function
then Function is a Asynchronous non blocking function
then The rules of :
then The return value of the function is A new promise object
yes then The return value of the incoming callback function :
1. If it's a promise object So that's it
2. If not one promise object , Then the result of the function will be packaged as a generated data promise object
var p1=new Promise(function(n1,n2){ var n=Math.random() n1(n) //n1 Called On behalf of p1 Generated data }) var re=p1.then(function(data){ console.log(data,111) return 200 }) console.log(222) re.then((data)=>{console.log(data,333)})Running results :
Program examples :
Running results :
2. Task queues and event loops
(1) The hardest part of asynchronous programming Queue classification of tasks And the cycle of events
(2) Task refers to js Running code in code
(3)fn() On behalf of fn The operation of the task , Script is also a task , The running of timer is also a task ,promise It's also a task
(4) The task is divided into Synchronous tasks And asynchronous tasks
Synchronization task : Synchronization task refers to the tasks queued on the main thread , Only the previous task was completed , To carry on with the next task .
Asynchronous task : Asynchronous task means not entering the main thread , And the tasks in the task queue , Only the task queue notifies the main thread , Some asynchronous task is ready to execute , This task will enter the main thread .
Examples of synchronization tasks :
function fn(){}
var a=new Array()
var b=fn()
Examples of asynchronous tasks :
setTimeout(fn,1000)
p1.then(fn)
console.log(123)
Program examples :
console.log(4) setTimeout(() => { setTimeout(()=>{console.log(6)},0) console.log(1) var p2 = new Promise((n1, n2) => { n1(1000) }) p2.then(()=>{console.log(7)}) }, 0) setTimeout(() => { setTimeout(() => {console.log(2)}, 200) var p3 = new Promise((n1, n2) => { n1(1000) }) p3.then(()=>{console.log(8)}) console.log(2) }, 0) var p1 = new Promise((n1, n2) => { n1(1000) }) p1.then(() => {console.log(3)}) console.log(5)Running results :
Queue priority of asynchronous tasks : The asynchronous macro task executes first Then execute asynchronous micro tasks
The event loop
After the task is started : There may be new tasks during internal execution
1. Perform the synchronization task first
2. Add a new macro task to the queue Add a new asynchronous micro task
3. Executing asynchronous micro tasks
Those are macro tasks :
macro : A script is a macro task
Script run Perform the first macro task :
边栏推荐
- 分布式 session 的4个解决方案,你觉得哪个最好?
- TFX airflow experience
- 2022.7.8 eth price analysis
- Opengauss source code, what ide tools are used to manage, edit and debug?
- Is it you who are not suitable for learning programming?
- Day 19 of leetcode
- 树的孩子兄弟表示法
- Share an esp32 relay
- 为什么登录时,明明使用的是数据库里已经有的账号信息,但依旧显示“用户不存在”?
- @Valid的作用(级联校验)以及常用约束注解的解释说明
猜你喜欢

Newline required at end of file but not found.

Four methods of modifying MySQL password (suitable for beginners)

POC simulation attack weapon - Introduction to nucleus (I)

【图像隐藏】基于DCT、DWT、LHA、LSB的数字图像信息隐藏系统含各类攻击和性能参数附matlab代码

使用PyTorch的TensorBoard-可视化深度学习指标 | PyTorch系列(二十五)

Day 8 of DL

Which users are suitable for applying for rapidssl certificate

@Valid的作用(级联校验)以及常用约束注解的解释说明

写英文IEEE论文的技巧
![[elm classification] classification of UCI data sets based on nuclear limit learning machine and limit learning machine, with matlab code](/img/50/f063cec7610015a062e3773d9916cd.png)
[elm classification] classification of UCI data sets based on nuclear limit learning machine and limit learning machine, with matlab code
随机推荐
CNN training cycle reconstruction - hyperparametric test | pytorch series (XXVIII)
trivy【1】工具扫描运用
@The function of valid (cascade verification) and the explanation of common constraint annotations
Center-based 3D Object Detection and Tracking(基于中心的3D目标检测和跟踪 / CenterPoint)论文笔记
unity中物体碰撞反弹(学习)
windbg
Flutter神操作学习之(满级攻略)
Day 8 of DL
Opengauss Developer Day 2022 sincerely invites you to visit the "database kernel SQL Engine sub forum" of Yunhe enmo
[brother hero's July training] day 27: picture
First knowledge of C language -- operators and keywords, define, pointer
Flutter God operation learning (full level introduction)
unordered_ The hash function of map and the storage mode of hash bucket
Is the interface that can be seen everywhere in the program really useful? Is it really right?
selenium+pytest+allure综合练习
Job 7.27 IO process
为什么登录时,明明使用的是数据库里已经有的账号信息,但依旧显示“用户不存在”?
Introduction to the reduce() function in JS
2020.7.7 eth price analysis
ORACLE BASICFILE LOB字段空间回收SHRINK SPACE的疑惑






