【问题标题】:async.series function unable to access member of container classasync.series 函数无法访问容器类的成员
【发布时间】:2021-04-26 19:38:50
【问题描述】:

我在类的成员函数中使用了async.series,但无法访问此引用,因此无法从async.series 函数中访问该类的成员 - 有什么解决方法吗?

如何在类中声明async series 模式并访问async series 模式中的类成员?

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()

以下是输出:

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)

【问题讨论】:

标签: node.js async.js


【解决方案1】:

这是因为您使用function(cb) 而不是(cb)=&gt;{}。如果您尝试控制台记录this,您将看到this 是函数。这与范围界定有关。 https://www.w3schools.com/js/js_scope.asp 将为您提供更多信息。另一个有更多信息的地方:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    相关资源
    最近更新 更多