-1

I have used async.series within a member function of a class but unable to access this reference and thus the members of that class from within the async.series functions - any workaround for this?

How can I declare async series pattern within a class and access the class members within the async series pattern ?

async = require("async");
class X {
  constructor() {
    this.member = 1;     /*< --- member declaration*/
  }
  f(){
    async.series([      /*< --- async declaration*/
      function (cb) {
        console.log('s1')
        cb();
      },
      function (cb) {
        console.log('s2')
        console.log(this.member)      /*< --- member access failing here*/
        cb();
      }
    ], function(){
      console.log('here')
    });
  }
}

(new X()).f()

Following is the output:

s1
s2
TypeError: Cannot read property 'member' of undefined
    at /home/runner/KnowledgeableFrequentStatistic/index.js:14:26
    at /home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:2948:28
    at replenish (/home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:440:21)
    at /home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:445:13
    at eachOfLimit$1 (/home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:471:34)
    at awaitable (/home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:208:32)
    at eachOfSeries (/home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:658:16)
    at awaitable (/home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:208:32)
    at /home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:2947:9
    at awaitable (/home/runner/KnowledgeableFrequentStatistic/node_modules/async/dist/async.js:208:32)
Ulysses
  • 5,616
  • 7
  • 48
  • 84
  • Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – jonrsharpe Apr 26 '21 at 11:27

1 Answers1

1

This is because you use function(cb) instead of (cb)=>{}. If you try console logging this, you will see that this is the function. This has to do with scoping. https://www.w3schools.com/js/js_scope.asp will give you some more info. Another place with some more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Bas
  • 337
  • 2
  • 16