Skip to content

Commit 07b9040

Browse files
authored
Create 08. Promise.md
1 parent f541f09 commit 07b9040

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Machine Coding/08. Promise.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
### Implement a Promise that takes a function following the common callback-last error-first style.
2+
3+
4+
```js
5+
/**
6+
* Converts a callback-based function into a function that returns a Promise.
7+
*
8+
* @param {Function} func - The function to promisify (follows callback-last, error-first convention).
9+
* @returns {Function} - A new function that returns a Promise.
10+
*/
11+
export default function promisify(func) {
12+
if (typeof func !== 'function') {
13+
throw new TypeError('Expected a function');
14+
}
15+
16+
return function (...args) {
17+
// Return a new Promise
18+
return new Promise((resolve, reject) => {
19+
// Call the original function with an additional callback
20+
func(...args, (err, result) => {
21+
if (err) {
22+
// Reject the promise if there's an error
23+
reject(err);
24+
} else {
25+
// Resolve the promise with the result
26+
resolve(result);
27+
}
28+
});
29+
});
30+
};
31+
}
32+
```
33+
34+
### Explanation
35+
#### Validate Input:
36+
37+
* Check if the input `func` is a valid function. If not, throw a `TypeError`.
38+
#### Return a New Function:
39+
40+
* The returned function preserves the original function's signature (i.e., it returns a function that takes any number of arguments).
41+
#### Create a Promise:
42+
43+
* Inside the returned function, we wrap the execution in a Promise.
44+
* The callback-based function `(func)` is called with all the arguments spread (`...args`), and we append a custom callback as the last argument.
45+
#### Handle the Callback:
46+
47+
* The custom `callback` follows the error-first convention ((err, result)):
48+
* If err exists (i.e., the operation failed), reject the Promise with the error.
49+
* Otherwise, resolve the Promise with the result.

0 commit comments

Comments
 (0)