Показать сообщение отдельно
  #8 (permalink)  
Старый 31.08.2021, 20:41
Аватар для voraa
Профессор
Отправить личное сообщение для voraa Посмотреть профиль Найти все сообщения от voraa
 
Регистрация: 03.02.2020
Сообщений: 2,756

Сообщение от Aetae
P.S. И да, работать как требует dc65k оно не будет: осле первых трёх количество запросов будет нарастать без контроля, а должно быть всегда три.)
Заменим fetch на другую функцию и проверим
<html>
<script>
const fakefetch = (url) =>{
	return new Promise (res => {
		dt = (Math.random()*2+1)*1000 | 0
		setTimeout(() => res({url:url, dt: dt}), dt)
	})
}
const sendRequests = (requests, maxRequestsCount) => {
    
    return new Promise(resolve => {
 
        const responses = Array.from({length: requests.length}, _ => null);
 
		let curUrlInd = 0;
		let requestDone = 0;
 
        
        for (let i = 0; i < maxRequestsCount; i++) {
            const request = requests[i];
			 
            makeRequest(requests[i], i);
        }
        curUrlInd = maxRequestsCount
 
        async function makeRequest(url, n) {
			console.log('Request', n)
            return fakefetch(url)
//                .then(result => result.json())
//                .catch(error => error)
                .then(result => {
                    responses[n] = result;
                })
                .finally (() => {
					requestDone ++;
					console.log('Done', n, requestDone)
					if (curUrlInd < requests.length) {
						makeRequest(requests[curUrlInd], curUrlInd);
						curUrlInd++;
					}
					if (requestDone === requests.length) {
						console.log ('Done All')
						resolve(responses);
					}
                });
        }
    });
}
 
    sendRequests([
        'https://jsonplaceholder.typicode.com/todos/2',
        'https://jsonplaceholder.typicode.com/todos/4',
        'https://jsonplaceholder.typicode.com/todos/10',
        'https://jsonplaceholder.typicode.com/todos/18',
        'https://jsonplaceholder.typicode.com/todos/20',
        'https://jsonplaceholder.typicode.com/todos/40',
        'https://jsonplaceholder.typicode.com/todos/100',
        'https://jsonplaceholder.typicode.com/todos/180'
    ], 3).then(response => {
        console.log(response);
    })
</script>
</html>


Нарастать не будет - новый запрос посылается, когда какой то из ранее посланных закончится.

Последний раз редактировалось voraa, 31.08.2021 в 20:47.
Ответить с цитированием