1

Is there anything in JavaScript that recognizes when a chain of method calls is finished?

Example

var myAPI = {
    foo : function() { ... return this; }
    bar : function() { ... return this; }
    baz : function() { ... return this; }
};

myAPI.foo().baz().bar();

In my example, when the last method in the chain is called I want it to save some data. Now I could have each method of myObjcall a save() function, but since each method is/may be updating that data, I'd rather wait until I'm finished with my chain. And I don't want to manually call save() after my chain. (Maybe the save() function isn't exposed in my API.)

I've heard a lot about "Promises", but looking on MDN, I don't think that's what I'm looking for. Maybe this is not a thing in Javascript. Have any of you heard of any such wizardry?

Community
  • 1
  • 1
Phil Tune
  • 3,154
  • 3
  • 24
  • 46
  • you need some kind of **callback** since your function calls execute some asynchronous code. Promises are just a nicer syntactic way to handle callbacks. – Pac0 Sep 10 '17 at 03:00
  • Promises would work fine for this. – Gerardo Sep 10 '17 at 03:01
  • 1
    Question has been asked lots of times before https://stackoverflow.com/questions/12679642/how-to-detect-chained-function-calls-in-javascript https://stackoverflow.com/questions/14123557/how-to-detect-the-end-of-a-method-chain-in-javascript https://stackoverflow.com/questions/1934247/javascript-detect-end-of-chained-functions – Andy Ray Sep 10 '17 at 03:01
  • well awesome, thank you sirs! – Phil Tune Sep 10 '17 at 03:05
  • 1
    How would you distinguish the cases of `myAPI.foo().baz().bar();` and `var baz = myAPI.foo().baz(); baz.bar();`, which one would expect to mean the same thing, but with your semantics, would write something out after the first statement? –  Sep 10 '17 at 03:40
  • I hate to be one of those guys that whines about a vote down, but reviewers really need to write comments explaining their downvote. It seems people do it just when they don't like a question, not because the question has any particular flaws. I wish SO would enforce that for reviewers since so much of the time they are whipping through these things without putting a great amount of thought into it. Okay, I'm finished whining. I appreciate the responses! – Phil Tune Sep 10 '17 at 11:50

0 Answers0