1 <!DOCTYPE HTML>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Demo: dojo/Deferred</title>
6 <link rel="stylesheet" href="style.css" media="screen">
7 </head>
8 <body>
9 <h1>Demo: dojo/Deferred</h1>
10 <ul id="userlist"></ul>
11 <!-- load dojo and provide config via data attribute -->
12 <script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js" data-dojo-config="isDebug: 1,async: 1,parSEOnLoad: 1"></script>
13 <script>
14 require(["dojo/Deferred","dojo/request","dojo/_base/array","dojo/dom-construct","dojo/dom","dojo/domReady!"],15 function(Deferred,request,arrayUtil,domConstruct,dom) {
16 /*var deferred = new Deferred(),17 userlist = dom.byId("userlist");
18
19 deferred.then(function(res){
20 arrayUtil.forEach(res,function(user){
21 domConstruct.create("li",{
22 id: user.id,23 innerHTML: user.username + ": " + user.name
24 },userlist);
25 });
26 },function(err){
27 domConstruct.create("li",{
28 innerHTML: "Error: " + err
29 },userlist);
30 });
31
32 // Send an HTTP request
33 request.get("users.json",{
34 handleAs: "json"}).then(
35 function(response){
36 // Resolve when content is received
37 deferred.resolve(response);
38 },39 function(error){
40 // Reject on error
41 deferred.reject(error);
42 }
43 );*/
44
45 //由于dojo/Deferred模块是Dojo的promise接口的主要实现,所以上面这个例子可以这样写:
46 var deferred = request.get("users.json",{
47 handleAs: "json"
48 });
49 deferred.then(function(res){
50 var userlist = dom.byId("userlist");
51 arrayUtil.forEach(res,function(user){
52 domConstruct.create("li",{
53 id: user.id,54 innerHTML: user.username + ": " + user.name
55 },userlist);
56 });
57 },function(err){
58 // This shouldn‘t occur,but it‘s defined just in case
59 alert("An error occurred: " + err);
60 });
61 });
62 </script>
63 </body>
64 </html>