capdragon
capdragon

Reputation: 14899

Chaining dojo Deferred

I'm having trouble wrapping my head around chaining functions with "then" and Deferred objects.

I would like to have multiple functions (processes) chained together so that after one function with Async call is completely done, the other starts, and so on.

Something like:

process1().then(process2()).then(process3());

I've followed many different tutorials that do it differently but i'm still not able to get a working example.

What am I missing?

Here is a Fiddle Link

Upvotes: 2

Views: 963

Answers (1)

Bourbia Brahim
Bourbia Brahim

Reputation: 14702

You missed the require part (require(["dojo/Deferred"]) ,modern dojo use AMD loading to load required modules, make reference in callback function that you'll use in your code .

Here is a working Fiddle

In the above fiddle I've select dojo as lib and add some coniguration as the below picture

dojo conifg in jsfiddle

Snippet below :

require(["dojo/Deferred",],function(Deferred){
	function process1() {
      var dfd = new Deferred();

      // perform some async logic; resolve the promise
      setTimeout(function () {
          $("#output").html("process 1 complete");
          dfd.resolve("process 1 complete");
      }, 1000);

      return dfd.promise;
  }
	
  function process2() {
      var dfd = new Deferred();

      // perform some async logic; resolve the promise
      setTimeout(function () {
          $("#output").html("process 2 complete");
          dfd.resolve("process 2 complete");
      }, 1000);

      return dfd.promise;
  }
  
  process1().then(function (){
    return process2();
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output">Start</div>

Also, note that you can make multiple chaining as demonstrated in this Fiddle

Upvotes: 2

Related Questions