Created
January 24, 2019 15:33
-
-
Save egorguscha/23103d0f7b4b2b98acad89dc2edd53e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const p1 = new Promise(resolve => setTimeout(resolve, 300, 'first promise')) | |
const p2 = new Promise(resolve => setTimeout(resolve, 200, 'second promise')) | |
const p3 = new Promise(resolve => setTimeout(resolve, 700, 'third promise')) | |
const p4 = new Promise(resolve => setTimeout(resolve, 500, 'fourth promise')) | |
const p5 = new Promise(resolve => setTimeout(resolve, 900, 'fifth promise')) | |
function concurrentCall(arrQueries, count) { | |
const sortRes = [] | |
return new Promise(resolve => { | |
function handlePromise(prom, index) { | |
return fetch(prom) | |
.then(res => res.json()) | |
.then(data => { | |
sortRes[index] = data | |
if (sortRes.length === arrQueries.length) { | |
resolve(sortRes) | |
console.log('ok') | |
} | |
}) | |
} | |
arrQueries.reduce((acc, prom, index) => { | |
if (index < count) { | |
return acc.then(handlePromise(prom, index)) | |
} | |
return acc.then(() => handlePromise(prom, index)) | |
}, Promise.resolve()) | |
}) | |
} | |
const g = [ | |
'https://jsonplaceholder.typicode.com/todos/1', | |
'https://jsonplaceholder.typicode.com/todos/2', | |
'https://jsonplaceholder.typicode.com/todos/3', | |
'https://jsonplaceholder.typicode.com/todos/4', | |
'https://jsonplaceholder.typicode.com/todos/5' | |
] | |
concurrentCall(g, 3).then(res => console.log(res)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment