consider the following:
import request = require("request");
class CFoo {
test:number;
async getItem(): Promise<number> {
var requestOptions = {
method: 'GET',
url: `https://www.google.com`,
headers: {
'cache-control': 'no-cache'
}
};
console.log('number is ' + this.test);
return new Promise<number>((resolve, reject)=>{
console.log('in promise... number is ' + this.test);
request(requestOptions, function (error, response, body) {
console.log('in async... number is ' + this.test);
if (error) throw new Error(error);
resolve(this.test);
});
});
}
constructor() {
this.test = 555;
}
}
var foo:CFoo = new CFoo();
foo.getItem().then(val=>console.info('returned ' + val));
As you can notice, i read value of test (555) in three situations:
- from the
getItem()
method call - from the promise executor
- from the
request()
callback function.
I was surprised to notice that in #3, test
is undefined!
I can understand that this
is not "a thing" in the executor/callback context,
as caller can't know the object and perform __thiscall
(c++ terminology).
1st question: Why wasn't test
included in the closure ?
2nd question: if request
callback didn't work, why did the promise executor ?
note, tried changing the lambda to anonymous function with same results.
Thanks.