is that when using a callback method, we usually just pass the callback to a function that will be called when finished to get some results. However, in Promise you attach the callback to the returned Promise object.
1.callback
callback function itself is a common name for us. We define it, but we will not execute it ourselves. It is eventually executed by others.
Advantages: easier to understand;
disadvantages: 1. High coupling, difficult maintenance, callback hell; 2. Only one callback function can be specified per task; 3. If there is no order between several asynchronous operations, you must also wait for the previous operation to end before performing the next operation.
2.Promise
ES6 provides us with a native constructor Promise. Promise represents an asynchronous operation that can separate the asynchronous object and callback function, and bind the callback function on this asynchronous operation through the .then method. Promise allows us to solve the problem of callback nesting through chain calls. Moreover, because the existence of a method like promise.all, it can make it simple to execute multiple operations at the same time. There are three states of the
promise object:
1)Fulfilled: Success state
2)Rejected: Failed state
3)Pending: Neither success nor failure state, it can be understood as the in-progress state
Promise's disadvantages:
1. When in an unfinished state, it is impossible to determine which stage it is currently in.
2. If the callback function is not set, errors inside Promise will not be reflected externally.
3. The Promise cannot be canceled. Once it is created, it will be executed immediately and cannot be cancelled in the middle.
If you want to know more about web front-end technology content, please follow Shang Silicon Valley Education!