Event queue (nextTick5)

Only records personal understanding: do not involve the underlying knowledge.

1. For chestnuts

```
console.log('script start');

setTimeout(function() {
console.log('setTimeout');
}, 0);

Promise.resolve().then(function() {
console.log('promise1');
}).then(function() {
console.log('promise2');
});

console.log('script end');

print:

script start

script end

promise1

promise2

setTimeout
```

2. eventLoop

`` `
Task (macro task): in the form of queue. In the browser environment (browser you can enter JavaScript / DOM domain from the inside), executed sequentially. And the task between two tasks, the browser can be updated rendering.


Mircotasks (micro tasks): micro-tasks are usually arranged on things occur directly after the execution of the current script, for example, to respond to a number of operations, in order to avoid paying the price of a new task.
mircotask callback queue after treatment, as long as no other execution among (mid-execution) codes; process or at the end of each task. During processing microtasks queue, newly added microtasks added to the end of the queue and is also performed.

This means that

script end performed before promise1, because the code is running must be completed before processing microtasks.

promise2 setTimeout before printing, because microtasks always perform a task before the next.

promise1 before promise2 print:

During processing microtasks queue, newly added microtasks added to the end of the queue and is also performed.

```

3. For chestnut 2

`` `
Here p state has been resolved

let p = Promise.resolve();
for(let i = 0; i < 5; i++){
a = p.then(()=>{
return new Promise((resolve, reject)=>{
console.log("test")
setTimeout(()=>{
console.log(i);
resolve()
}, 500)
})
})
}
console.log(p)
p.then(()=>{
console.log('完成')
})


Process analysis:

1. The
main code block task 1:

Sequentially performs: the assignment of p, for loop, p.then (callback), into microtasks queue. then

microtasks1: [1,2,3,4,5], performed next console.log (p); print

p.then (); performed

microtasks1:. [1,2,3,4,5,6] Since execution of this task has not ended, it is successively inserted into the queue.

2.
followed by the completion microtasks1 queue.

Each execution of: printing first 'test';

Followed by the setTimeout callback into task2, ... task6 task queue;

The last execution microtasks1 complete print queue

microtasks1 queue after the implementation, the back sequentially performed tasks

Then finally print out 0, 1, 2, 3, 4

```


4. For chestnut 3 (not know the right analysis)

Once the promise to solve the (settled), or has been resolved, they arranged a microtask callback when you call for it then.
`` `
The let P = Promise.resolve ();
for (the let I = 0; I <. 5; I ++) {
P = p.then (() => {
return new new Promise ((Resolve, Reject) => {
Console .log ( "Test")
the setTimeout (() => {
the console.log (I);
Resolve ()
}, 500)
})
})
}
the console.log (P)
p.then (() => {
Console. log ( 'complete')
})

 

Process analysis:

1. Promise.resolve () execution

Promise has been resolved.

2. for loop, a first P is already solved promise.
Thus promise.then () which is placed in callback queue microtask;

3. When the loop is executed for the second time, this time in a pending state promise. (Guess after this time will not push microtask callback queue, but will be pushed when the promise Resolve)

According to the above speculation at this time, other callback for loop
is temporarily absent microtask queue, whether the task, they are in (tasks macro task queue it or which particular place)

Similarly behind p.then

4. When this task is finished, perform microtask code.

Print "test", the setTimeout callback function, placed in the queue to be executed.

The next task execution

Print I; and performs Resolve (); case promise status change. The callback function then pushed into
microtask queue ();

And then it has been circulating the above process until the last

p.then (() => {
the console.log ( 'complete')
});

Print complete end;

Overall it is:

Promise
Test
0
Test
. 1
Test
2
Test
. 3
Test
. 4
is completed
`


5. Let me say vue of nextTick;

```
var callbacks = [];
var pending = false;

function flushCallbacks () {
pending = false;
var copies = callbacks.slice(0);
callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}


function nextTick (cb, ctx) {
var _resolve;
// callbacks 全局属性 所有的回调函数
callbacks.push(function () {
if (cb) {
try {
cb.call(ctx);
} catch (e) {
handleError(e, ctx, 'nextTick');
}
} else if (_resolve) {
_resolve(ctx);
}
});
if (!pending) {
pending = true;
if (useMacroTask) {
macroTimerFunc();
} else {
microTimerFunc();
}
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(function (resolve) {
_resolve = resolve;
})
}
}


The main three steps: (still very one-sided understanding, in the subsequent need to learn, and continue to understand)

1. nextTick itself pushed in the callback to the callback function.

2. pending status value, then task on a macro task (or micro-task) is not completed before, not to push the task queue again. This means that pending for some time, has been true. We have repeatedly nextTick convenient instead, each execution will be asynchronous operations once

3. macroTimerFunc. In fact, that is an asynchronous function (vue in setImmediate, MessageChannel, the setTimeout)
microTimerFunc (Promise or macroTimerFunc)

4. Task is determined using a macro or micro tasks according useMacroTask (specific circumstances unclear)

5. Then the task after the task executed, execution of the next
macro-or micro-task assignment.

```


6. Processing model (specifications)

`` `
A event loop as long as there will continue to perform the steps below:
1. Select the oldest tasks in a task queue, the user agent may choose any task queue, if there is no optional tasks, skip to the bottom microtasks step.
2. The top choice task to task is running.
3.Run: Run the selected task.
4. The event currently loop of the running task becomes null.
The task is removed from the front running task queue.
6.Microtasks: microtasks perform tasks checkpoint. (That is, the task execution queue microtasks)
7. Update rendering (Update at The Rendering) ...
8. If this is a worker event loop, but no task in the task queue, and closing WorkerGlobalScope object identifier is true, destruction event loop, discontinue these steps, and then run a worker in the definition section of the Web workers.
9. Return to first step.
`` `


7. microtasks (microtask checkpoint)

`
When the user agent to perform a microtask checkpoint, microtask checkpoint if a flag (flag) is false, the user agent must run the following steps:
1. The microtask checkpoint flag is set to true.
2.Microtask queue handling: If the event loop microtask queue is empty, skip to step VIII (Done).
3. Select the oldest in microtask a task queue.
4. Back to choose tasks set currently event loop of the running task.
5. Run the selected task.
6. The event currently loop of the running task becomes null.
7. Remove the run from the front microtask microtask the queue, then returns to step 2 (Microtask queue handling).
8.Done: Each environment settings object they are responsible event loop is the current event loop, give the environment settings object issued a notice of a rejected promises.
9. cleanup IndexedDB transaction.
10. microtask checkpoint of the flag is set to flase.

 

When calling?

1. When the context of the execution stack is empty, performing a microtask checkpoint.

The sixth step 2. In the event loop of (Microtasks: Perform a microtask checkpoint) to perform checkpoint, that is, after running the task, update before rendering.
`` `

Guess you like

Origin www.cnblogs.com/jiabaochuan/p/12108229.html