MIRROR: javascript for 馃悳's, a tiny runtime with big ambitions
1// Test async/promise handling with 'this' context
2
3class AsyncClass {
4 constructor() {
5 this.name = 'AsyncClass';
6 this.value = 100;
7 }
8
9 asyncMethod(arg) {
10 console.log('asyncMethod called:');
11 console.log(' this.name: ' + this.name);
12 console.log(' this.value: ' + this.value);
13 console.log(' arg: ' + arg);
14 return Promise.resolve(this.value + 10);
15 }
16
17 methodWithPromise() {
18 console.log('methodWithPromise called:');
19 console.log(' this.name: ' + this.name);
20 const self = this;
21
22 return Promise.resolve(this.value).then(function(v) {
23 console.log(' Inside .then(), this.name: ' + self.name);
24 console.log(' Inside .then(), this.value: ' + self.value);
25 return v * 2;
26 });
27 }
28
29 nestedAsync(helperFunc) {
30 console.log('nestedAsync called:');
31 console.log(' this.name: ' + this.name);
32 const result = helperFunc();
33 console.log(' After helper call, this.name: ' + this.name);
34 return result;
35 }
36}
37
38function helperFunction() {
39 return 'helper result';
40}
41
42const obj = new AsyncClass();
43
44console.log('=== Test 1: Async method ===');
45const p1 = obj.asyncMethod('test');
46console.log('Promise returned: ' + (typeof p1));
47
48console.log('\n=== Test 2: Method with promise chain ===');
49const p2 = obj.methodWithPromise();
50console.log('Promise returned: ' + (typeof p2));
51
52console.log('\n=== Test 3: Nested call with helper ===');
53obj.nestedAsync(helperFunction);
54
55console.log('\n=== All tests completed ===');