Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
840 views
in Technique[技术] by (71.8m points)

node.js - Chain functions in JavaScript

Is there a way to chain functions in JavaScript so when last function in chain is called we take into consideration all function in chain that was specified. Basically what I am trying to do is the same thing express-validator does: Something like this:

check('password').passwordValidator().optional();

I want to be able to call

check('password').passwordValidator();

and

check('password').passwordValidator().optional();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So you're looking for a sort of builder pattern? You can do that like this:

class Foo {
  _passwordValidator = false;
  _optional = false;

  passwordValidator() {
    this._passwordValidator = true;
    return this;
  }
  optional() {
    this._optional = true;
    return this;
  }

  doThing() {
    if (this._optional) { /* ... */ }
    if (this._passwordValidator) { /* ... */ }
  }
}

const foo = new Foo().passwordValidator().optional();

foo.doThing();

Edit: to more directly answer your question, there is no way to wait to do something until the current chain of method calls is done; you have to call a method like doThing() in the example to signal that you actually want to do the thing now.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...