Skip to content Skip to sidebar Skip to footer

How Pass Parameters To Downstream Function With Done() Or Next()

I am new to next(), done() etc. and am struggling with propagating parameters between serial executions/chaining of possibly otherwise asynchronous functions. I want to force seria

Solution 1:

You need to pass parameters to .resolve(), then use .then()

functionf1(arg1a, arg1b) {

  return $.Deferred(function(dfd) {
    //do something with arg1a, arg1b// you can alternatively call `.resolve()` without passing parameters// when you are finished doing something with `arg1a`, `arg1b`,// which should call chained `.then()` where `f2` is called
    dfd.resolve(arg1a, arg1b)
  }).promise();
}

functionf2(arg2a, arg2b) {
  // Do something with arg2a and arg2b AFTER f1 has fully run.
}

f1(arg1, arg2)
.then(function() {
  // call `f2` heref2('#{arg2a}', '#{arg2b}');
})
// handle errors
.catch(function(err) { // alternatively use `.fail()`console.log(err)
});

jsfiddle https://jsfiddle.net/wuy8pj8d/

Solution 2:

You've almost got it right except you've forgotten to wrap the code you want to execute in the future (when done is eventually called) inside a function:

f1('#{arg1a}', '#{arg1b}').done(function(){
  f2('#{arg2a}', '#{arg2b}')
});

This also works with regular callbacks. For example, say you've defined f1 to accept a callback instead of a promise, you'd then do:

f1('#{arg1a}', '#{arg1b}',function(){
  f2('#{arg2a}', '#{arg2b}')
});

Nothing special here. There's no separate syntax for forcing callbacks to accept custom arguments, just wrap it in another function.

This also works for variables thanks to closures:

var a='#{arg1a}', b='#{arg1b}';
var c='#{arg2a}', d='#{arg2b}';

f1(a,b).done(function(){
  f2(c,d)
});

The variables c and d will be accessible within done().

Post a Comment for "How Pass Parameters To Downstream Function With Done() Or Next()"