—- synchronous task or asynchronous task —- synchronous task into the main thread, asynchronous task into the Event Table and register functions. When the specified Event completes, the Event Table moves this function to the Event Queue. If the tasks in the main thread are empty after execution, the Event Queue will read the corresponding function and enter the main thread for execution. This process is repeated over and over again, known as an Event Loop.

Synchronous tasks are executed directly, while asynchronous tasks are classified into macro-tasks and micro-tasks. Macro task: overall Script setTimeout setInterval microtask: Promise process.nexttick

Console. log(' mainline console'); SetTimeout (function() {console.log(' macro task setTimeout'); // If setTimeout is set to a time, the macro task Event Queue will register its callback function. }) new Promise(function(resolve) {console.log(' microtask Promise '); // The new Promise function executes immediately. The Promise is essentially a synchronized resolve(); }). Then (function() {console.log(' microtask then'); // Then function is distributed to microtask Event Queue}) // Execution order result: main thread console, microtask PROMISE, microtask then, macro task setTimeoutCopy the code

2. Prove that promises are essentially synchronous

SetTimeout (function() {console.log(' macro task setTimeout'); // If setTimeout is set to a time, the macro task Event Queue will register its callback function. }) new Promise(function(resolve) {console.log(' microtask Promise '); // The new Promise function executes immediately. The Promise is essentially a synchronized resolve(); }). Then (function() {console.log(' microtask then'); }) console.log(' main thread console'); // Execution sequence results: microtask PROMISE, main thread console, microtask then, macro task setTimeoutCopy the code

Async is wrapped around promise, so it is essentially a synchronous task

async function async1() { console.log('async1 start') await async2() console.log('async1 end') } async function async2() {console.log('async2')} async1() console.log('script end') // The output is async1 start, async2, script end, async1 endCopy the code