当前位置:网站首页>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 :
边栏推荐
- Collision and rebound of objects in unity (learning)
- MySQL is shown in the figure. The existing tables a and B need to be associated with a and B tables through projectcode to find idcardnum with different addresses.
- tfx airflow 使用体验
- IO流:节点流和处理流详细归纳。
- Hardware standard
- Interpretation of cesium3dtilesets using customshader and examples of Omni effects
- JS 事件对象 offsetX/Y clientX Y PageX Y
- Is it you who are not suitable for learning programming?
- Job 7.27 IO process
- Newline required at end of file but not found.
猜你喜欢

What "posture" does JD cloud have to promote industrial digitalization to climb to a "new level"?

Retainface use error: modulenotfounderror: no module named'rcnn.cyton.bbox'

Representation of children and brothers of trees

Should programmers choose outsourcing companies
![[image defogging] image defogging based on dark channel and non-mean filtering with matlab code](/img/39/6266eb14deac9f38b7e95f7291067e.png)
[image defogging] image defogging based on dark channel and non-mean filtering with matlab code
![[leetcode] 13. linked list cycle · circular linked list](/img/58/c8796bb5ed96d09325b8f2fa6a709e.png)
[leetcode] 13. linked list cycle · circular linked list

@The function of valid (cascade verification) and the explanation of common constraint annotations

JS 事件对象2 e.charcode字符码 e.keyCode键码 盒子上下左右移动

MySQL索引学习

【TA-霜狼_may-《百人计划》】图形3.7 移动端TP(D)R架构
随机推荐
Commissioning experience of ROS
"29 years old, general function test, how do I get five offers in a week?"
Digital twin agriculture - Smart agriculture rice processing plant has changed from "watching the sky to eat" to "knowing the sky to work"
Special network technology virtual host PHP version setting
P6118 [JOI 2019 Final]珍しい都市 题解
@The function of valid (cascade verification) and the explanation of common constraint annotations
[TA frost wolf \u may hundred people plan] Figure 3.5 early-z and z-prepass
没法预测明天的涨跌
Is the interface that can be seen everywhere in the program really useful? Is it really right?
What "posture" does JD cloud have to promote industrial digitalization to climb to a "new level"?
JS event object offsetx/y clientx y pagex y
trivy【1】工具扫描运用
Interpretation of cesium3dtilesets using customshader and examples of Omni effects
【信号处理】基于高阶统计量特征的通信系统中微弱信号检测附matlab代码
Usage of delegate
P6118 [joi 2019 final] solution to the problem of Zhenzhou City
[software testing] - unittest framework for automated testing
Arm32进行远程调试
JS中的reduce()函数介绍
[TA frost wolf \u may - hundred people plan] Figure 3.7 TP (d) r architecture of mobile terminal






