javascript - How to pass callback closure parameters to external environment variables in JS
typecho
typecho 2017-07-05 10:59:29
0
3
879

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<

typecho
typecho

Following the voice in heart.

reply all(3)
phpcn_u1582

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.

淡淡烟草味

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.

阿神

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template