Skip to content

Instantly share code, notes, and snippets.

@monochromer
Created May 16, 2019 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monochromer/fe779676fd4f23b11250d437752f1a34 to your computer and use it in GitHub Desktop.
Save monochromer/fe779676fd4f23b11250d437752f1a34 to your computer and use it in GitHub Desktop.
Future: Асинхронность на фьючерах без состояния
// © Timur Shemsedinov
// https://www.youtube.com/watch?v=22ONv3AGXdk
// https://github.com/HowProgrammingWorks/Future
class Future {
constructor(executor) {
this.executor = executor;
}
static of(value) {
return new Future(resolve => resolve(value));
}
chain(fn) {
return new Future((resolve, reject) => this.fork(
value => fn(value).fork(resolve, reject),
error => reject(error),
));
}
map(fn) {
return this.chain(value => Future.of(fn(value)));
}
fork(successed, failed) {
this.executor(successed, failed);
}
promise() {
return new Promise((resolve, reject) => {
this.fork(
value => resolve(value),
error => reject(error),
);
});
}
}
const futurify = fn => (...args) => new Future((resolve, reject) => {
fn(...args, (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment