1.1 Callback function
Callback function: Pass function A as a parameter to call another function B, then A is the callback function. [Recommended: JavaScript video tutorial]
Some examples named callbacks
function How many dogs do you have(fn){ fn('a dog') }function count dogs(number){ console.log(quantity) } How many dogs do you have (count dogs) // one dog
Anonymous callback
function How many dogs do you have(fn){ fn('a dog') } How many dogs do you have (function(number){console.log(number) }) // a dog
Common examples
Callback functions are used in jQuery, and anonymous callbacks are used here.
$("#btn").click(function(){ console.log('click on me') })
1.2 Callback Hell (Callback Disadvantage 1)
Callback hell: refers to the situation where callbacks are nested too much, making the code difficult to understand.
let info = []function How many dogs do you have(fn){ fn('a dog') }function How many cats do you have(fn){ fn('a cat') }function knows(quantity,callback){ info.push(quantity) console.log(info) if(callback){ callback() } }//Start calling. If there are a few more layers than this, it will be difficult to understand how many dogs you have (function(number of dogs){ console.log(number of dogs) Got it(number of dogs, function(){ How many cats do you have(function(number of cats){ console.log(number of cats) Got it (number of cats) }) }) })
1.3 How to solve the problem without using Promise
Use named functions instead of anonymous functions
let info = []function How many dogs do you have(fn){ fn('a dog') }function How many cats do you have(fn){ fn('a cat') }function knows(quantity,callback){ info.push(quantity) console.log(info) if(callback){ callback() } }function tells you the number of cats (number of cats){ console.log(number of cats) Got it (number of cats) }function continue counting(){ How many cats do you have (tell you the number of cats) }function tells you the number of dogs (number of dogs){ console.log(number of dogs) Got it (number of dogs, keep counting) } How many dogs do you have (tell you the number of dogs) // It doesn't seem to be much better. . .
1.4 The callback methods are different and need to be remembered separately (callback disadvantage 2)
readFile('C:\1.txt',function (error, data) { // callback in node.js read file method if(error) { console.log('success') console.log(data.toString()) } else { console.log('Failed to read file') } }) $.ajax({ //Callback url:'/2.txt' in the ajax method in jQuery success: function(response) { console.log('success') }, error: function(){ console.log('failure') } })
Promises are a solution to asynchronous programming that is more reasonable and powerful than traditional solutions - callbacks and events. It was first proposed and implemented by the community. ES6 wrote it into the language standard, unified its usage, and provided Promise objects natively.
3.1 Implementation principle
ES6 stipulates that the Promise object is a constructor used to generate Promise instances. By returning an instance of the Promise object inside the function, you can use the properties and methods of the Promise for the next step.
function function name(){ return new Promise(function(resolve, reject) { // ... some code if (/* asynchronous operation successful */){ resolve(value); // Called when the asynchronous operation is successful and pass the result as a parameter } else { reject(error); // Called when asynchronous failure occurs, passing the error as a parameter } }) }
3.2 Calling logic
Neither S1 nor E1 reported an error, execute S2 (resolve execution, the system thinks it is done, and no error is reported)
If either S1 or E1 reports an error, execute E2 (reject execution, the system thinks it is not done, and reports an error)
Front-end (vue) entry to mastery course: enter learning
4.1 Properties and methods of Promise
property
Promise.prototype represents the prototype method of the Promise constructor
Promise.prototype.then()
Return a Promise. It requires at most two parameters: the Promise's success and failure callback functions.
Promise.prototype.catch()
Return a Promise and handle rejection. Equivalent to Promise.prototype.then(undefined, onRejected)
Promise.prototype.finally()
The finally() method returns a Promise. After executing then() and catch(), the callback function specified by finally will be executed. Avoid the situation where the same statement needs to be written once in then() and catch().
Promise.all(iterable)
Returns a Promise instance. After all the promises in the iterable parameters are resolved, the callback completes the resolve.
Promise.race(iterable)
Returns a promise, accompanied by the return value of the promise object or the error reason for rejection, as long as there is a promise object in the iterable that "resolve" or "reject".
Promise.resolve()
Returns a Promise object that resolves with the given value. But if this value is a thenable (that is, with a then method), the returned promise will "follow" the thenable object and adopt its final state (referring to resolved/rejected/pending/settled); if the incoming value itself is a promise Object, then the object is returned as the return value of the Promise.resolve method; otherwise, the promise object is returned with this value as the success status.
Promise.reject()
Returns a Promise object with the reason parameter for rejection.
4.2 Rewrite the example in callback hell into Promise form
You can see that after using Promise, the logic becomes very intuitive and written more completely.
When Promise is nested in Promise, that is, when Promise is chained - pay attention to the failure of information transmission. When we use Promise chain, if each step requires data from the previous step, parameters need to be passed. Successfully passed through resolve. Parameters, if failed, pass parameters through reject. If you forget to pass parameters, you will not get the desired result.
resolve returns successful data to the next callback
Reject returns failed data to the next callback.
Pass a parameter to resolve here and change it to an example of failure. Do not pass parameters to reject first. If it fails, the next callback will not get the data.
Pass parameters to reject
We can see that even if the failure callback is passed, the next success callback is still executed. Since it is not known () returns undefined by default, it is equivalent to the failure having been processed. When both success and failure are processed, the next callback will be implemented.
Change it to what is expected, that is, it will not be called if it fails.
Short form for not calling on failure
After the above situation is executed, the success callback in .then (except for dogs) is not executed. Let's add a failure callback to see
You can also return resolve so that subsequent successful callbacks can be executed.
4.3 Application
Loading the image writes the loading of the image as a Promise. Once the loading is completed, the state of the Promise changes.
const preloadImage = function (path) { return new Promise(function (resolve, reject) { const image = new Image(); image.onload = resolve; image.onerror = reject; image.src = path; }); };
The combination of Generator function and Promise (for details, see the reference link, Ruan Yifeng’s tutorial)
5.1 await
successful case
Use try catch in case of failure
Use await with try catch, which is more complete.
Promise objects can be used to change ordinary functions into Promise-returning forms to solve the problem of callback hell.
Understand the success and failure calling logic of Promise and can flexibly adjust it.
Understand the core knowledge, use it first, and slowly integrate and absorb the knowledge.
The above is the detailed content of the example analysis of the principle and use of ES6 Promise!