4.7.2 Promise.all Example
by dimitrs_papadimitriou
HTML
<script src="https://rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>
JavaScript
class Either {
map(f) {
throw new Error('You have to implement the method map!');
}
matchWith(pattern) {
throw new Error('You have to implement the method matchWith!');
}
bind(f) {
return this.matchWith({
left: (e) => new Left(e),
right: (v) => f(v)
})
}
}
class Right extends Either {
constructor(value) {
super();
this.value = value;
}
map(f) {
return new Right(f(this.value))
}
matchWith(pattern) {
return pattern.right(this.value)
}
}
class Left extends Either {
constructor(value) {
super();
this.value = value;
}
map(f) {
return new Left(this.value);
}
matchWith(pattern) {
return pattern.left(this.value)
}
}
Either.prototype.toPromise = function () {
return new Promise((resolve, reject) => {
this.matchWith({
left: (error) => reject(error),
right: (result) => resolve(result)
})
})
}
var toPromise = either => either.toPromise();
Promise.prototype.matchWith = function (pattern) {
return this.then(pattern.right).catch(pattern.left)
}
Promise.prototype.bind = function (f) {
return this.then(f)
}
Promise.prototype.map = function (f) {
return this.then(f)
}
var mockClientRepository = ({
getById: (id) =>
new Promise((resolve, reject) => {
setTimeout(() => {
var client =
[{ id: 1, name: 'rick', age: 29, employeeId: 1 },
{ id: 2, name: 'morty', age: 25, employeeId: 3 }]
.find(client => client.id === id);
if (client)
resolve(client)
else
reject("no client found")
}, 1000)
})
})
var mockEmployeeRepository = ({
getById: (id) =>
new Promise((resolve, reject) => {
setTimeout(() => {
var employee = [{ id: 1, name: 'jim', age: 29 },
{ id: 2, name: 'jane', age: 25 }]
...