Home  >  Q&A  >  body text

javascript - How to pass callback closure parameters to external environment variables in JS

Like the question, how to pass the formal parameter data in the closure to external variables

var outer;
var map = new BMap.Map("allmap");
var point = new BMap.Point(116.331398,39.897445);
var gc = new BMap.Geocoder();
gc.getLocation(point, function(rs){
   var addComp = rs.addressComponents;
    //how to store this string to variable outer;
   //outer = addComp.province + ", " + addComp.city + ", " + addComp.district + ", " +      addComp.street + ", " + addComp.streetNumber);
});

Using assignment can only ensure that the data in the closure is valid. It will be invalid after exiting. Using new to allocate memory has no effect. I am short of time and have no time to learn JS, so I am shameless to ask segmentfault>3<

typechotypecho2638 days ago836

reply all(3)I'll reply

  • phpcn_u1582

    phpcn_u15822017-07-05 11:01:29

    Use ajax async:false but the problem remains? Post the code and take a look. According to common sense, it should be OK.
    Other methods
    1: Asynchronous values ​​and logic related to asynchronous values ​​can be processed in the then logic of promise.
    2: Use generator and yield synchronization writing to process your logic
    3: You can also use async function directly.

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-07-05 11:01:29

    Your code assignment method is correct. The so-called [invalid after exiting] may be a control flow problem like this:

    var x = 0
    setTimeout(() => {
      // 这里 x 是 1
      x = 1
    }, 1000)
    
    // 这里 x 还是 0
    console.log(x)

    In your code, gc.getLocation If it is an asynchronous call like the above example, then the code execution order cannot be guaranteed according to the order in which the code is written. Therefore, if you access the outer variable directly in subsequent code, you are likely to get the old value before the asynchronous call is completed.

    reply
    0
  • 阿神

    阿神2017-07-05 11:01:29

    You can now define an external variable outside, such as the Object type, and then pass it in as a parameter. By assigning a value to the Object internally, you can transfer the value to the outside

    reply
    0
  • Cancelreply