Friday 5 May 2017

How to control scope in node callbacks?

Playing around i found that the this object across callbacks on the same object stays the same. Is it wise to use this for scope control as follows.

process.stdin.once('data', (chunk) => {
    this.count = 0;
})

process.stdin.on('data', (chunk) => {
    this.count += chunk.length;
});

process.stdin.on('end', () => {
    console.log("N of bytes ${this.count}");
});

As I do not see this often, I'm wondering if anything is wrong with it or better methods of doing the same exist.



via adeniyi Adeosun

No comments:

Post a Comment