-
-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
3be2d44
commit 2d01a07
Showing
3 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
'use strict'; | ||
|
||
class Future { | ||
#executor; | ||
|
||
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 new Future((resolve, reject) => | ||
this.fork( | ||
(value) => | ||
new Future((resolve, reject) => { | ||
try { | ||
resolve(fn(value)); | ||
} catch (error) { | ||
reject(error); | ||
} | ||
}).fork(resolve, reject), | ||
(error) => reject(error), | ||
), | ||
); | ||
} | ||
|
||
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); | ||
}); | ||
}); | ||
|
||
module.exports = { Future, futurify }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters