Всем привет.
Прошу проверить код.
Было так:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
'use strict'
var obj = {count: 0, maxCount: 5};
while (isNeedContinue(obj)) {
doAnything();
console.log("Что-то еще...");
}
function doAnything() {
obj.count++;
console.log("doAnything", obj.count);
}
function isNeedContinue(obj) {
console.log("isNeedContinue", obj, obj.count < obj.maxCount);
return obj.count < obj.maxCount
}
</script>
</head>
</html>
Функция doAnything стала асинхронной.
Переделал так:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
'use strict'
var obj = {count: 0, maxCount: 5};
*!*$.when((function recursive() {*/!*
*!*if*/!* (isNeedContinue(obj)) {
*!*return*/!* doAnything()*!*.then(function () {*/!*
console.log("Что-то еще...");
*!*return recursive()*/!*
})
}
})())
.done(function (res) {
console.log("Done", res);
})
.fail(function (err) {
console.log("Fail", err);
});
function doAnything() {
*!*var deferred = $.Deferred();*/!*
*!*setTimeout(function () {*/!*
obj.count++;
console.log("doAnything", obj.count);
//if (obj.count==3) deferred.reject(new Error("err!"));
*!*deferred.resolve(obj);*/!*
*!*}, 1000)*/!*
*!*return deferred.promise()*/!*
}
function isNeedContinue(obj) {
console.log("isNeedContinue", obj, obj.count < obj.maxCount);
return obj.count < obj.maxCount
}
</script>
</head>
</html>
Все ли путем?
Технически, все вроде работает. Но вдруг я что-то упустил?
Осваиваю JS, буду благодарен за любую конструктивную критику.