1. Synchronous callback function
Execute immediately, continue to execute after it is completely executed, and will not be placed in the callback queue
E.g:
- Callback functions related to array traversal
- Promise of excutor function (in use
new Promise()
to create a new object when passed to the constructor function parameters Promise)
//代码演示
let arr = [1,2,3];
arr.forEach(function (item) {
//遍历回调,该同步回调函数不会放入列队,一上来就要执行完
console.log(item);
})
console.log('forEach()之后');
Output result:
2. Asynchronous callback function
Will not be executed immediately, will be placed in the callback queue for future execution
E.g:
- Timer callback
- ajax callback
- Promise success or failure callback
//代码演示
setTimeout(function () {
//该异步回调函数,会放在队列中
console.log('setTimeout()正在执行');
},0);
console.log('setTimeout()之后');
//结果:先输出“setTimeout()之后”,最后输出“setTimeout()正在执行”