-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy path2776-convert-callback-based-function-to-promise-based-function.js
More file actions
54 lines (53 loc) · 1.58 KB
/
2776-convert-callback-based-function-to-promise-based-function.js
File metadata and controls
54 lines (53 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* 2776. Convert Callback Based Function to Promise Based Function
* https://leetcode.com/problems/convert-callback-based-function-to-promise-based-function/
* Difficulty: Medium
*
* Write a function that accepts another function fn and converts the callback-based function into
* a promise-based function.
*
* The function fn takes a callback as its first argument, along with any additional arguments
* args passed as separate inputs.
*
* The promisify function returns a new function that should return a promise. The promise should
* resolve with the argument passed as the first parameter of the callback when the callback is
* invoked without error, and reject with the error when the callback is called with an error as
* the second argument.
*
* The following is an example of a function that could be passed into promisify.
* function sum(callback, a, b) {
* if (a < 0 || b < 0) {
* const err = Error('a and b must be positive');
* callback(undefined, err);
* } else {
* callback(a + b);
* }
* }
*
* This is the equivalent code based on promises:
*
* async function sum(a, b) {
* if (a < 0 || b < 0) {
* throw Error('a and b must be positive');
* } else {
* return a + b;
* }
* }
* */
/**
* @param {Function} fn
* @return {Function<Promise<number>>}
*/
var promisify = function(fn) {
return async function(...args) {
return new Promise((resolve, reject) => {
fn((result, error) => {
if (error) {
reject(error);
} else {
resolve(result);
}
}, ...args);
});
};
};