简体   繁体   English

在Node.js异步管道中调用正确的对象方法

[英]Correct object method calls in Node.js async pipelines

I want to use some Node.js async pipeline operations (such as parallel and waterfall ) to call instance methods inside an object. 我想使用一些Node.js async管道操作(例如parallelwaterfall )来调用对象内的实例方法。

I am using the following format to preserve the correct this reference inside the pipeline functions, since, normally, inside pipeline functions this references the pipeline object itself. 我使用以下格式在管道函数内部保留正确的this引用,因为通常在管道函数内部this引用管道对象本身。

var jobThis = this;
async.waterfall(
    [
        function(cb) { jobThis.getParseInstalls(cb); },
        function(prev, cb) { jobThis.getParseIAPs(prev, cb); },
    ],
    callback
);

I want the stages of the pipeline to be able to access (but not modify) a settings object belonging to the wrapping object. 我希望管道的各个阶段能够访问(但不能修改)属于包装对象的设置对象。

I feel like this constitutes bad style. 我觉得这样的风格很糟糕。 Is there a cleaner way to achieve this goal? 有没有更清洁的方法来实现这一目标? Am I simply not supposed to use methods and async ? 我根本不应该使用方法和async

In the end, I realized that simply using function.bind was the cleanest way to do this (and also, self is a bit clearer than anything else): 最后,我意识到简单地使用function.bind是做到这一点的最干净的方法(而且self比其他任何东西都更清晰):

var self = this;
async.waterfall([
     self.getParseInstalls.bind(self),
     self.doSomethingElse.bind(self),
 ],
 callback
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM