MIRROR: javascript for 馃悳's, a tiny runtime with big ambitions
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

at master 63 lines 1.9 kB view raw
1// Test that 'this' works with regular functions in async callbacks 2 3class AsyncRegularFunctionTest { 4 constructor(name) { 5 this.name = name; 6 this.value = 100; 7 } 8 9 testPromiseWithRegularFunction() { 10 console.log('=== testPromiseWithRegularFunction ==='); 11 console.log('Before promise: this.name = ' + this.name); 12 13 return Promise.resolve(42).then(function(val) { 14 console.log('Inside .then() with function:'); 15 console.log(' typeof this: ' + typeof this); 16 console.log(' this.name: ' + this.name); 17 console.log(' this.value: ' + this.value); 18 return val + 1; 19 }); 20 } 21 22 testPromiseWithArrowFunction() { 23 console.log('\n=== testPromiseWithArrowFunction ==='); 24 console.log('Before promise: this.name = ' + this.name); 25 26 return Promise.resolve(42).then((val) => { 27 console.log('Inside .then() with arrow:'); 28 console.log(' typeof this: ' + typeof this); 29 console.log(' this.name: ' + this.name); 30 console.log(' this.value: ' + this.value); 31 return val + 1; 32 }); 33 } 34 35 testMethodCallingPromiseWithFunction() { 36 console.log('\n=== testMethodCallingPromiseWithFunction ==='); 37 const self = this; 38 console.log('Before promise: this.name = ' + this.name); 39 40 return Promise.resolve(1).then(function() { 41 console.log('In .then() with function:'); 42 console.log(' this.name: ' + this.name); 43 console.log(' self.name: ' + self.name); 44 return self.value; 45 }); 46 } 47} 48 49const obj = new AsyncRegularFunctionTest('TestObject'); 50 51obj.testPromiseWithRegularFunction().then(function(result) { 52 console.log('Result 1: ' + result); 53}); 54 55obj.testPromiseWithArrowFunction().then((result) => { 56 console.log('Result 2: ' + result); 57}); 58 59obj.testMethodCallingPromiseWithFunction().then((result) => { 60 console.log('Result 3: ' + result); 61}); 62 63console.log('\n=== All tests queued ===');