How does js get the return value of onclick-bound functions and the return value after Ajax calls?

  node.js, question

There are two main problems:
1. how can the value returnData obtained by calling Ajax through get be returned to foo ()?
2. how to assign the return value returnData to the outermost returnData after onclick is executed
//To simplify and abstract the problems I have encountered is as follows:

 var returnData;
 for(var i=0;   i<length;  I plus)
 element.onclick = helper(i);
 function helper(i){
 return function(){
 returnData = foo(i);
 function foo(x){
 var returnData;
 //get function is the encapsulation of Ajax get method.
 get(url, {}, function(text){
 ReturnData = text plus x;
 return returnData;

Only answer the first:No solution, your opening method is wrong.

It seems that you still use it again.SynchronizationBut when it comes to ajax, you have to switch toAsynchronousThe thinking of.

Ever wonder why ajax uses callback functions?

Because the network is sometimes delayed, waiting for requests means blocking, which is not possible. Therefore, the function returns immediately after ajax calls. But then the data will not be available-because you don’t know when the data will come. Since we can’t take the initiative to get the data, we can use another method, that is, pass in the data processing operation-this is callback.

AndReturn as return value, which is a feature of synchronous operation, cannot be done here.


  • Use callback

  • Use Promise

  • Early adopters ES 7 new feature async