Skip to content

Instantly share code, notes, and snippets.

@egorguscha
Created June 5, 2019 16:06
Show Gist options
  • Save egorguscha/f9ea12ce1593ae831a2a38ed017811c2 to your computer and use it in GitHub Desktop.
Save egorguscha/f9ea12ce1593ae831a2a38ed017811c2 to your computer and use it in GitHub Desktop.
// example 1
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, limit) {
const sortRes = []
let count = 0
let totalCount = arrQueries.length
return new Promise(resolve => {
function handlePromise(prom, index) {
return fetch(prom)
.then(res => res.json())
.then(data => {
sortRes[index] = data
count++
if (count >= totalCount) {
resolve(sortRes)
}
})
}
arrQueries.reduce((acc, prom, index) => {
if (index < limit) {
console.log(index)
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, 4).then(res => console.log(res))
// example 2
var source = [
{ url: 'http://abc/1', time: 1000, value: 1 },
{ url: 'http://abc/2', time: 500, value: 2 },
{ url: 'http://abc/3', time: 300, value: 3 },
{ url: 'http://abc/4', time: 300, value: 4 },
{ url: 'http://abc/5', time: 100, value: 5 }
]
function handle(sources, limit) {
var limit = 0
var index = limit
var response = []
var totallimit = sources.length
return new Promise(resolve => {
for (var i = 0; i < limit; i++) {
getNext(i)
}
function getNext(i) {
var item = sources[i]
if (!item) {
console.log('everything in work right now')
return
}
setTimeout(() => {
console.log(item.value)
response[i] = item.value
limit++
if (limit >= totallimit) {
console.log('have response')
resolve(response)
} else {
var nextIndex = index
index++
getNext(nextIndex)
}
}, item.time)
}
})
}
handle(source, 5).then(data => {
console.log(data)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment