简体   繁体   English

javascript - 检测链接函数的结束?

[英]javascript - detect end of chained functions?

Today I'm working on a pet project using chained function calls, and I'm curious how I might detect when the last function in the chain is executed.今天我正在使用链式函数调用处理一个宠物项目,我很好奇如何检测链中的最后一个函数何时被执行。 For example:例如:

func1('initial data').func2().func3().func4();

And after func2-4 have finished working on 'initial data' I'd like to detect when func4 is done.在 func2-4 完成对“初始数据”的处理后,我想检测 func4 何时完成。 Since func4() isn't always the last function in the chain, aka it could end at .func3() or .func5() for example, or I could mix my function calls up depending on what I'm trying to do, I'm trying to think of a way to detect no more function calls are being done but I'm not getting very far.由于 func4() 并不总是链中的最后一个函数,也就是说它可以以 .func3() 或 .func5() 结束,或者我可以根据我想要做的事情混合我的函数调用,我试图想出一种方法来检测没有更多的函数调用正在完成,但我并没有走得很远。

You can't. 你不能

Besides, if they are not chained: 此外,如果它们没有链接:

var v = func1('initial data');
v = v.func2();
v = v.func3();
v = v.func4();

What would you consider to be the last function? 您认为最后一个功能是什么? Every function is the last function in it's own chain, but if you finalise something after each step, that won't work. 每个函数都是它自己链中的最后一个函数,但是,如果您在每个步骤之后都完成了某些操作,那将无法正常工作。

Just make a function that you call last to finalise the process. 只需创建一个最后调用的函数即可完成该过程。

The traditional approach is to put whatever you want done after the final function on the next line: 传统方法是将您要完成的所有操作放在下一行的最终功能之后:

func1('initial data').func2().func3().func4();
allFunctionsDone();

;) ;)

You can write the sequencer, which will help you to do this for you. 您可以编写音序器,这将帮助您为自己执行此操作。 Instead of executing direct calls, shift the names of the functions and call them one by one. 不要执行直接调用,而要移位函数的名称,然后一一调用它们。 Something like this 像这样

executeSequence(func1('init_dat'),[
    'func2',
    'func3',
    'func4'
]);

they on supabase-js can do that magic.他们在supabase-js 上可以做到这一点。 but it will make your function chain is asynchronous.但它会使你的函数链是异步的。

how?如何? just simply implements Promise-like function chain.只是简单地实现了类似 Promise 的函数链。 in this case, I will use class instead.在这种情况下,我将改用 class。

class Counter {
  constructor() {
    this.count = 0;
  }

  // here's the magic
  then(resolve) {
    console.log(this.count);
    resolve();
  }

  add() {
    this.count++;
    return this;
  }
}

you do still need run last chain function.你仍然需要运行最后一个链函数。

new Counter().add().then();

but, you also can do this way.但是,您也可以这样做。

await new Counter().add();

you also can make it to have return value你也可以让它有返回值

then(resolve) {
  resolve(RETURN_GOES_HERE);
}

this method is best to use imo if your function chain is asynchronous.如果您的函数链是异步的,则此方法最好使用 imo。

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

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