Answer the question
In order to leave comments, you need to log in
The output of the results of the chain of promises works strangely, why?
Hello!
There is a more global task, but I implemented it on a simple test, where the result is identical. A simple example. We consider the sums of an arithmetic progression in a chain of successive promises. In reality, instead of a progression, a rather long (several seconds) process is considered, so a pseudo-delay is inserted into the arithmetic progression to emulate this situation. We display the result on the page. The code:
$(document).ready(function()
{
TestFunc();
});
//Арифметическая прогрессия
function arithmeticProgression(n)
{
delay(100);
return (n !== 0) ? n + arithmeticProgression(n-1) : 0;
}
//Эмуляция задержки
function delay(ms)
{
var date = Date.now();
var curDate = null;
do
{
curDate = Date.now();
} while (curDate-date < ms);
}
//Тестовая функция
function TestFunc()
{
const counter = 10;
$('body').html('');
for (var i = 0; i < counter; i++)
{
$('body').append($("<div id='" + i + "'>i=" + i + "<span> Новый</span></div>"));
}
//Начало цепочки промисов
let chain = Promise.resolve();
var results = [];
for(let i=0; i<counter; i++)
{
chain = chain.then(function()
{
$('#' + i + ' span').text(' В процессе');
return TestPromise(i, 0);
})
.then(function(result)
{
$("#" + i + " span").text(' ' + result);
results.push(result);
});
}
chain.then(function()
{
console.log('All done!');
});
}
//Промис расчета арифметической прогрессии
function TestPromise(n, delay)
{
delay = delay || 0;
return new Promise(function(resolve)
{
/*setTimeout(function()
{
resolve("arithmetic progression(1, " + n + ")=" + arithmeticProgression(n));
}, delay);*/
resolve("arithmetic progression(1, " + n + ")=" + arithmeticProgression(n));
});
}
Answer the question
In order to leave comments, you need to log in
Promises themselves are asynchronous
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question