operating mechanism
Single-threaded asynchronous mechanism
Synchronous: Execute in program order
Asynchronous: timer, ajax read files
After the execution of the synchronous program is completed, the asynchronous program is executed. If the timer is queued later, then the timer must be executed later, no matter how long it is set. so the timer is inaccurate
process.nextTick(()=>{
//同步
//VUE中的
})
同步代码执行之后,异步代码之行之前
setImmediate(()=>{
})
当前事件循环代码执行之后
There are two concepts of running stack and task queue. Synchronous code is placed in the running stack, and then the asynchronous program will be placed in the task queue.
事件循环:不断检测任务队列中有没有任务。例如,setTImeout设置时间,时间到了就会放到任务队列中,然后不断检测,按到先来先执行的顺序来执行。
give an example
setImmediate(()=>{
console.log(1)
})
process.nexTick(()=>{
console.log(2)
})
console.log(3)
setTimeout(()=>{console.log(4)},0)
setTimeout(()=>{console.log(5)},100)
console.log(6)
//结果 362415
Macrotasks and Microtasks
Macro task: timer, ajax, read file
Micro task: promise.then
Execution sequence:
1. Synchronization program
2. process.nextTick()
3. Micro task
4. Macro task
5 setImmediate
extends the above example
setImmediate(()=>{
console.log(1)
})
process.nexTick(()=>{
console.log(2)
})
console.log(3)
setTimeout(()=>{console.log(4)},0)
setTimeout(()=>{console.log(5)},100)
console.log(6)
new Promise((resolve)=>{
console.log(7)//在运行栈中执行
}).then(()=>{
console.log(8)
})
//结果 36728415
Promise object
//promise es6 new object
let p = new Promise((resolve) => {
console.log('hello')
resolve('world')
})
p.then((data) => {
console.log(data)
})
//输出只有hello 只有调用resolve才会调用then
axios.get('').then((res)=>{
console.log(res);
})
//get方法返回的是promise对象,reslove传回res
async function
1. The return value of the async function is a promise object
async function fun(){
return 1;
}
//相当于
function fun(){
return new Promise((resolve)=>{
resolve(1);
})
}
fun().then((data)=>{
console.log(data);
//这样就拿到了返回值
})
2. await usage
Asynchronous code is more like synchronous code
let p = new Promise((resolve)=>{
resolve(1);
})
let p2 = new Promise((resolve)=>{
resolve(2);
})
async =