Skip to content

Instantly share code, notes, and snippets.

@fogrew
Created November 22, 2017 16:48
Show Gist options
  • Save fogrew/b412bd34bbe64dbb1d00a413afa8591b to your computer and use it in GitHub Desktop.
Save fogrew/b412bd34bbe64dbb1d00a413afa8591b to your computer and use it in GitHub Desktop.
Пытаюсь резолвить промисы пачками по N штук, а не все сразу, как делает Promise.all
'use strict';
const flatten = (arr) => [].concat.apply([], arr)
/**
* Accepts an iterate collection of promises, resolves them by bundles with accumulate results
*
* @param {Array} promises - array of unresolved promises
* @param {object} settings - object with any settings
* @param {number} settings.from - number of promise, from which to begin new iteration
* @param {number} settings.iteration - number of promises for one iteration
* @returns {Array} - returns promise
*/
const debouncePromises = async (promises, settings) => {
const defaults = {
from: 0,
iteration: 10
}
const options = Object.assign({}, defaults, settings)
let pack = []
let results = []
for (let index = 0; index < promises.length; index += options.iteration) {
pack = promises.slice(index, index + options.iteration)
results.push(await Promise.all(pack))
}
return flatten(results)
}
module.exports = debouncePromises
import test from 'ava'
import debouncePromises from './index.js'
test('жить охуенно', t => {
const promises = new Array(30).fill(() => {
return new Promise(resolve => {
resolve('result')
})
})
return debouncePromises(promises)
.then(result => {
t.true(
result.every(el =>
el() === 'result'
)
)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment