我構建了一個隨機化承諾的演示。它構建了一組可以解析1到100的promise。然後對這個數組進行洗牌並獲得結果。它的工作原理,我們可以看到它以隨機順序輸出。 (fiddle)隨機化使用ajax的承諾
var promises = [];
for (var i = 0; i < 100; i++) {
promises.push(new Promise(function(resolve, reject) {
resolve(i);
}));
}
// http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
shuffle(promises).forEach(function(r) {
r.then(function(v) {
\t $('#out').append('<div>'+v+'</div>')
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="out">
</div>
然而,當我在承諾包括阿賈克斯,結果就是不再是隨機的。輸出有時無序,但大多按升序排列。與前一個演示不同的部分是構建承諾數組。 fiddle
var promises = [];
for (var i = 0; i < 100; i++) {
promises.push(new Promise(function(resolve, reject) {
$.ajax({
url: '/echo/json/',
data: { json: JSON.stringify({"v": i}) },
method: 'POST',
success: function(rs) {
resolve(rs.v);
}
});
}));
}
爲什麼?
有意義。感謝您的解釋。 – Fabricator