i have some problems with my class design and promises. I am trying to listen for a change variable by calling my promise cb recursively. And when networkResponse returns a valid (not null) token i am trying to resolve it or it will check 500 times by delaying 500 ms in each call.
Here is the my class with simplified now:
class Tokenizer {
constructor(page) {
this.page = page;
this.token = null;
this.tries = 500;
this.page.on('response', this.onNetworkResponse.bind(this));
}
async onNetworkResponse(response) {
if (condition) {
let resp = await response.text();
let regex = /access_token=([\w\d]+)/g;
let _token = regex.exec(response);
this.token = _token[1];
}
}
getToken() {
return new Promise(function cb(resolve, reject) {
console.log(this.tries + ' remaining');
if (--this.tries > 0 && !this.token) setTimeout(() => cb(resolve, reject), 500);
else (this.tries <= 0) ? reject('Try') : resolve(this.token);
});
}
}
And I call the promise like this:
const t = new Tokenizer();
let test = async () => {
let token = await t.getToken();
}
test();
However i am losing this scope inside of cb function. If someone can answer this problem i would really appreciate it
For whom have a problem like this i've just updated my getToken function like this:
getToken() {
var cb = (resolve, reject) => {
console.log(this.tries);
if (--this.tries > 0 && !this.token) setTimeout(() => cb(resolve, reject), 500);
else (this.tries <= 0) ? reject('Try') : resolve(this.token);
}
return new Promise(cb);
}