-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathd-resolvers.js
More file actions
52 lines (41 loc) · 1.04 KB
/
d-resolvers.js
File metadata and controls
52 lines (41 loc) · 1.04 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
'use strict';
// Need node.js 22
const sumAsync = (a, b, callback) => {
if (typeof a !== 'number') return;
if (typeof b !== 'number') return;
setImmediate(() => {
callback(a + b);
});
};
// Old approach
const old = async () => {
let resolve, reject;
const promise = new Promise((resolved, rejected) => {
resolve = resolved;
reject = rejected;
});
setTimeout(reject, 1000, new Error('Timed out'));
sumAsync(2, 3, resolve);
const result = await promise;
console.log({ result });
};
old();
// Alternative approach
const alternative = async () => {
const promise = new Promise((resolve, reject) => {
sumAsync(4, 5, resolve);
setTimeout(reject, 1000, new Error('Timed out'));
});
const result = await promise;
console.log({ result });
};
alternative();
// New approach
const modern = async () => {
const { promise, resolve, reject } = Promise.withResolvers();
setTimeout(reject, 1000, new Error('Timed out'));
sumAsync(6, 7, resolve);
const result = await promise;
console.log({ result });
};
modern();