admin管理员组

文章数量:1390457

I am currently learning alot more about callback functions and want to create my own callback functions with a success and failure.

I have written for a Person object a game of rock paper sissors

Person = (function() {
  function Person(name) {
    this.name = name;
  }

  Person.prototype.randomRps = function() {
    var choices, randomChoice;
    choices = ["rock", "paper", "sissor"];
    return randomChoice = choices[Math.floor(Math.random() * choices.length)];
  };

  Person.rockPaperSissor = function(player1, player2) {
    return player1.randomRps() === player2.randomRps();
  };

  return Person;

})();

I want to call Person.rockPaperSissor(p1,p2).then(...) but don't know how I should write this .then() function to chain it to the .rockPaperSissor()

Similar to how jQuery has $.get() and a .success() and error() functions to chain.

Thanks!

I am currently learning alot more about callback functions and want to create my own callback functions with a success and failure.

I have written for a Person object a game of rock paper sissors

Person = (function() {
  function Person(name) {
    this.name = name;
  }

  Person.prototype.randomRps = function() {
    var choices, randomChoice;
    choices = ["rock", "paper", "sissor"];
    return randomChoice = choices[Math.floor(Math.random() * choices.length)];
  };

  Person.rockPaperSissor = function(player1, player2) {
    return player1.randomRps() === player2.randomRps();
  };

  return Person;

})();

I want to call Person.rockPaperSissor(p1,p2).then(...) but don't know how I should write this .then() function to chain it to the .rockPaperSissor()

Similar to how jQuery has $.get() and a .success() and error() functions to chain.

Thanks!

Share Improve this question asked Sep 5, 2014 at 21:53 Mohamed El MahallawyMohamed El Mahallawy 13.9k13 gold badges55 silver badges87 bronze badges 5
  • What you want is a Promise Implementation. If you are fortable using a feature that isn't available in all browsers, you can use the native Promise implementation that is available on some modern browsers. – Kevin B Commented Sep 5, 2014 at 21:54
  • 6 You don't have any asynchrony; there is no reason to do that. – SLaks Commented Sep 5, 2014 at 21:54
  • 1 Have a look at this: schier.co/post/method-chaining-in-javascript – jfrej Commented Sep 5, 2014 at 21:56
  • @SLaks agreed - I was asking this for the sake of simplicity but it'd be in the context of async. – Mohamed El Mahallawy Commented Sep 5, 2014 at 22:05
  • 1 @MohamedElMahallawy - probably worth mocking that up in the question, otherwise the answers won't meet what you're interested in. – nrabinowitz Commented Sep 5, 2014 at 22:09
Add a ment  | 

2 Answers 2

Reset to default 5

You just need to return this at your function

Person.rockPaperSissor = function(player1, player2) {
    this.state = player1.randomRps() === player2.randomRps();
    return this;
};

Person.then = function() {
    var x = this.state;
};

Assuming that something in Person.rockPaperSissor is async, you need to return some sort of Promise object. As others have noted, if the result here is synchronous, then there's no point in this particular misdirection. JQuery provides an implementation in DeferredObject; if you want to write your own, you'd need to work out what methods this object should support.

To take a relatively simple case, you could make a Promise class that only supported .then like this:

function Promise() {
    // start unresolved
    this.resolved = false;
    // init list of callbacks to fire on resolution
    this.callbacks = [];
}

Promise.prototype = {
    then: function(callback) {
        if (this.resolved) {
            // if resolved, fire immediately
            callback();
        } else {
            // otherwise, queue up the callback for later
            this.callbacks.push(callback);
        }
    },

    resolve: function() {
        this.resolved = true;
        // fire all callbacks
        this.callbacks.forEach(function(callback) {
            callback();
        });
    }
};

Then, in your async function, you'd do something like:

Person.rockPaperSissor = function(player1, player2) {
    var promise = new Promise();

    doSomethingAsync(function callback() {
        promise.resolve();
    });

    return promise;
};

In your specific case, .then won't be super-useful unless you expose the results of the rockPaperSissor function as persistent state on Person; if you want to pass the result to the callbacks, you'll need slightly more involved handling to pass arguments to your callbacks and potentially handle failure cases.

本文标签: javascriptHow to create my own then() functionStack Overflow