Показать сообщение отдельно
  #1 (permalink)  
Старый 11.07.2017, 13:23
Интересующийся
Отправить личное сообщение для SergeyERjs Посмотреть профиль Найти все сообщения от SergeyERjs
 
Регистрация: 03.07.2017
Сообщений: 19

Рекурсия промисов. Все правильно?
Всем привет.
Прошу проверить код.

Было так:
<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, буду благодарен за любую конструктивную критику.

Последний раз редактировалось SergeyERjs, 11.07.2017 в 13:48.
Ответить с цитированием