Analysis of the Return Function and Usage in JS

Tune function, what is a callback function? Many beginners are not very clear, feeling, don’t understand, not to use!

In fact, if it is understood, after a function is executed, the function is to be executed after the required specific data is not executed, and there is no penetration in the medicine!

Function getData (Callback) {// Here we assume that data setTimeout (function () {// assumes we get the data info var info = { “ID”: 1, “name”: ‘Zhang three’} // Received data after data Callback (INFO) // This is a callback function}, 1000)
   
The above code can clearly tell you what is a callback function! Maybe you still don’t quite understand, what does this callback do?

GetData (Check) Function getData (Callback) {// Here we assume that data setTimeout (function () {// assumes we get data info VAR INFO = {“ID”: 1, “name”: ‘Zhang three’} // Get data, execute the function method Callback (info) // This is the callback function}, 1000)} Function Check (data) {IF ( Data.id == 1) {console.log (‘Verification success, can pass’)}}
  Look at the above code, there are two methods, getData and check, we have implemented the getData method, and pass the Check as a parameter to getData, then CHECK is the callback function! 
What is the role of this callback function, how to use it? If you have understood the meaning of the callback function, then you will understand his usage, how to remember how to use him in the actual project!

Looking at the following code, I wrote a practical application:

//VUE framework, other frameworks can be modified ! ! ! // User Rights Verification Specific: created () {// Takes the method of obtaining data in this hook function, the verification method is used as a callback to getData (check)} method: {// In this, first you have to have The two methods used in the CREATED hook function Function getData (Callback) {// request user information to the backend // Here we assume that data setTimeout is acquired from the backend (function () {// assumes we get the data info VAR INFO = {“ID”: 1, “name”: ‘Zhang three’} // After the data is obtained, the function method Callback (info) // is the callback function, and after obtaining the user information, verify his permissions}, 1000 }} Function check (data) {// Verify user rights if (data.id == 1) {// verification permission condition, according to actual setting console.log (‘authentication success, can pass’) // authority , What can be done} else {console.log (‘verification failed, disabled traffic’) // No permissions, what can be done}}}

 Summary   
The above is a small-editing function and use, I hope to help everyone. If you have any questions, please leave a message, the small package will promptly Reply to everyone. Thank you very much for your support of Tumi Cloud Website!
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment