简体   繁体   中英

sort array while async.map running

Im using async map to execute a function and fetch some stats for every item in the array.

async.map(myarray,myfunc,function(err,res) ...

Meanwhile, might get sorted and change indexes by user interaction. 可能会通过用户交互进行排序并更改索引。 How would this fair considering is trying to modify the array. 试图修改数组,这公平

When you pass the myarray to async.map() , it creates a copy of the array synchronously. So, you can modify myarray all you want; async.map() will simply operate on a copy of the original array and return a new array. Try running the example below:

 var array = [1, 2, 3]; function timesTwo(n, done) { setTimeout(function() { done(null, n * 2); }, 2000); } $(document).ready(function() { setTimeout(function() { array.pop(); $('#pop').text(array); }, 1000); async.map(array, timesTwo, function(err, result) { $('#result').text(result); $('#original').text(array); }); }); 
 span { color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/async/1.5.2/async.js"></script> <p> 0ms: Original array passed to async.map(): <span>1,2,3</span></p> <p> 1000ms: Pop last item of original array: <span id="pop"></span></p> <p> 2000ms: Result of async.map(): <span id="result"></span></p> <p> 2000ms: Original array: <span id="original"></span></p> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM