Skip to content

Instantly share code, notes, and snippets.

@tastywheat
Created March 3, 2017 17:02
Show Gist options
  • Save tastywheat/26f2771fdd7ab8a500fb6490fbc7d0cb to your computer and use it in GitHub Desktop.
Save tastywheat/26f2771fdd7ab8a500fb6490fbc7d0cb to your computer and use it in GitHub Desktop.
bacon js batch async requests
var Bacon = require('baconjs');
var stream = new Bacon.Bus();
function keyF(event) {
return event.url;
}
function limitF(groupedStream, groupStartingEvent) {
return groupedStream.bufferWithTime(200);
}
var counter = 0;
var resultStream =
stream
.groupBy(keyF, limitF)
.flatMap(function (obs) {
return obs;
})
.flatMap(function (requests) {
console.log('FETCHING!!')
var promise =
new Promise((resolve, reject) => {
setTimeout(function () {
resolve({requests, response: counter++})
// reject({requests, response: 'wtfff'})
}, 2000);
})
return Bacon.fromPromise(promise, true);
});
resultStream.onError(function (opts) {
opts.requests.forEach(request => {
request.error(opts.response)
})
})
resultStream.onValue(function (opts) {
opts.requests.forEach(request => {
request.success(opts.response)
})
});
stream.push({
url: 'AAA',
message: '1111',
success: function (res) {
console.log('done', this.message, res)
},
error: function (err) {
console.log('ERROR', err)
}
})
setTimeout(function () {
stream.push({
url: 'AAA',
message: '2222',
success: function (res) {
console.log('done', this.message, res)
},
error: function (err) {
console.log('ERROR', err)
}
})
}, 150)
setTimeout(function () {
stream.push({
url: 'AAA',
message: '3333',
success: function (res) {
console.log('done', this.message, res)
},
error: function (err) {
console.log('ERROR', err)
}
})
}, 1500)
stream.push({
url: 'BBB',
message: '4444',
success: function (res) {
console.log('done', this.message, res)
},
error: function (err) {
console.log('ERROR', err)
}
})
stream.push({
url: 'BBB',
message: '5555',
success: function (res) {
console.log('done', this.message, res)
},
error: function (err) {
console.log('ERROR', err)
}
})
stream.push({
url: 'BBB',
message: '66666',
success: function (res) {
console.log('done', this.message, res)
},
error: function (err) {
console.log('ERROR', err)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment