-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromisify.js
46 lines (39 loc) · 914 Bytes
/
promisify.js
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
// tags: #promise #callback
function promisify(fn) {
return (...args) => {
return new Promise((res, rej) => {
fn(...args, (err, data) => {
if (err) rej(err);
else res(data);
});
});
};
}
/* test code */
function testRunner(fn) {
function query(arg, callback) {
// callback arguments are (err, data)
console.log("->", arg);
if (arg) callback(null, { message: "ok" });
else callback({ err: "params illegal" });
}
// callback style
function myCallback(err, data) {
if (err) console.log("x", err);
else console.log("<-", data);
}
query(1, myCallback);
query(null, myCallback);
// promise style
const pquery = fn(query);
function chain(p) {
p.then((data) => {
console.log("<-", data);
}).catch((err) => {
console.log("x", err);
});
}
chain(pquery(1));
chain(pquery(null));
}
testRunner(promisify);