1

After each of my promises I perform a then, in this then I check if the user wishes to cancel the promise chain.

this.getData
.then(function(data){
    self.shouldContinue(self.myNextMethod, data);
})
///more promises

Here is the check to see if the chain should continue:

p.shouldContinue = function(cb, args){

    if(this.cancelCurrentRequest) {

        if(typeof this.currentRequest.abort === 'function')this.currentRequest.abort();
        return $.Deferred(function (d){ return d.reject();}).promise();
    }

    this.currentRequest = cb.apply(this,args);
    return this.currentRequest;
};

The problem I am having is passing arguments to the method if it should continue.

For example, I am passing 'data' from getData then this needs to be passed to myNextMethod.

Currently it's undefined.

panthro
  • 22,779
  • 66
  • 183
  • 324
  • Use [`.call()`](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Function/call) instead of [`.apply()`](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) – Andreas Jun 23 '15 at 11:44

1 Answers1

1

Reading the documentation helps a lot:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

The apply method takes two arguments - the first is the thisArg (the context) and the second is an array of arguments.

There are two possible solutions to your problem:

1.Use the exact code that was given to you in the other thread

   .then(function() {
    return shouldContinue(getMoreData,arguments);
   })

arguments is a special array-like object in JavaScript available inside a function that contains all the arguments passed into that function

2.Use call like this:

   .then(function(data) {
    return shouldContinue(getMoreData,data);
   })

   p.shouldContinue = function(cb, data){
       ...
      this.currentRequest = cb.call(this,data);
   };

Documentation for call:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

Community
  • 1
  • 1
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • Thanks very much. Quick question, what does 'this' mean in cb.apply(this,args); – panthro Jun 23 '15 at 12:49
  • I'm also getting a new error. In the method that is called in shouldContinue I need to access this, but it comes back as undefined. Why? – panthro Jun 23 '15 at 12:53