1. Avoid directly accessing iterator in for-loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ary = [1, 2, 3, 4, 5]; | |
for (var i=0; i<ary.length; i++) { | |
somePromise.then(function () { | |
console.log(ary[i]); | |
}); | |
} |
2 3 4 5 5 instead of 1 2 3 4 5 which is expected.
The reason of failure is that when somePromise is resolved and console.log(ary[i]) is about to executed, the value of i could be incremented already.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ary = [1, 2, 3, 4, 5]; | |
for (var i=0; i<ary.length; i++) { | |
(function (element) { | |
somePromise.then(function () { | |
console.log(element); | |
}); | |
}(ary[i]); | |
} |
PS. This fix let you correctly access each element in the array but not guaranteed in the order of original array. i.e. you may see 1 3 2 4 5.
Because the resolved timing of each somePromise in the loop is asynchronous against iteration.
No comments:
Post a Comment