Dojo Tutorials:Getting Started with Deferreds源代码和例子执行汇总

19 篇文章 0 订阅
8 篇文章 0 订阅
本文通过三个示例详细介绍了Dojo框架中 Deferred 对象的使用,包括发起HTTP请求获取JSON数据并处理响应,简化代码实现,以及 Deferred 的链式调用。示例展示了如何处理成功和失败的情况,以及如何对数据进行转换和呈现。通过这些例子,读者可以深入理解Dojo中异步操作的管理方式。
摘要由CSDN通过智能技术生成

例子一

对一个json文件发起请求,得到结果后返回结果。解析失败返回错误。


<!DOCTYPE HTML>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Demo: dojo/Deferred</title>

		<link rel="stylesheet" href="style.css" media="screen">
	</head>
	<body>
		<h1>Demo: dojo/Deferred</h1>

		<ul id="userlist"></ul>

		<!-- load dojo and provide config via data attribute -->
		<script src="dojo/dojo.js" data-dojo-config="isDebug: 1, async: 1, parseOnLoad: 1"></script>
		<script>
			require(["dojo/Deferred", "dojo/request", "dojo/_base/array", "dojo/dom-construct", "dojo/dom", "dojo/domReady!"],
			function(Deferred, request, arrayUtil, domConstruct, dom) {
				var deferred = new Deferred(),
					userlist = dom.byId("userlist");

				deferred.then(function(res){
					arrayUtil.forEach(res, function(user){
						domConstruct.create("li", {
							id: user.id,
							innerHTML: user.username + ": " + user.name
						}, userlist);
					});
				},function(err){
					domConstruct.create("li", {
						innerHTML: "Error: " + err
					}, userlist);
				});

				// Send an HTTP request
				request.get("users.json", {
					handleAs: "json"}).then(
					function(response){
						// Resolve when content is received
						deferred.resolve(response);
					},
					function(error){
						// Reject on error
						deferred.reject(error);
					}
				);
			});
		</script>
	</body>
</html>

json文件的内容如下:

[
	{ "id": 1, "username": "Tom", "name": "Cage" },
	{ "id": 2, "username": "Jack", "name": "Smith" },
	{ "id": 3, "username": "Kenan", "name": "Brown" }
]

成功后的结果:

 

失败后的结果(如果访问不到这个json文件的话):

 例子二

和例子一很像,就是代码写法上有区别,更简洁了。代码如下:


<!DOCTYPE HTML>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Demo: dojo/Deferred with dojo/request</title>

		<link rel="stylesheet" href="style.css" media="screen">
	</head>
	<body>
		<h1>Demo: dojo/Deferred with dojo/request</h1>

		<ul id="userlist"></ul>

		<!-- load dojo and provide config via data attribute -->
		<script src="dojo/dojo.js" data-dojo-config="isDebug: 1, async: 1, parseOnLoad: 1"></script>
		<script>
			require(["dojo/request", "dojo/_base/array", "dojo/dom-construct", "dojo/dom", "dojo/domReady!"],
				function(request, arrayUtil, domConstruct, dom) {
					var deferred = request.get("users.json", {
						handleAs: "json"
					});
					deferred.then(function(res){
						var userlist = dom.byId("userlist");

						arrayUtil.forEach(res, function(user){
							domConstruct.create("li", {
								id: user.id,
								innerHTML: user.username + ": " + user.name
							}, userlist);
						});
					},function(err){
						// This shouldn't occur, but it's defined just in case
						alert("An error occurred: " + err);
					});
			});
		</script>
	</body>
</html>

执行结果:略。

原来声明一个defer 代码是:

                var deferred = new Deferred(),
					userlist = dom.byId("userlist");

				deferred.then(function(res){
					arrayUtil.forEach(res, function(user){
						domConstruct.create("li", {
							id: user.id,
							innerHTML: user.username + ": " + user.name
						}, userlist);
					});
				},function(err){
					domConstruct.create("li", {
						innerHTML: "Error: " + err
					}, userlist);
				});

现在是:

                    var deferred = request.get("users.json", {
						handleAs: "json"
					});
					deferred.then(function(res){
						var userlist = dom.byId("userlist");

						arrayUtil.forEach(res, function(user){
							domConstruct.create("li", {
								id: user.id,
								innerHTML: user.username + ": " + user.name
							}, userlist);
						});
					},function(err){
						// This shouldn't occur, but it's defined just in case
						alert("An error occurred: " + err);
					});

写法更简单明了。

例子三:Chaining 链式调用

json文件依旧是:

[
	[ 1, "Tom", "Cage" ],
	[ 2, "Jack", "Smith" ],
	[ 3, "Kenan", "Brown" ]
]

源代码文件是(console.log 语句是本人添加):


<!DOCTYPE HTML>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Demo: Chaining Deferreds</title>

		<link rel="stylesheet" href="style.css" media="screen">
	</head>
	<body>
		<h1>Demo: Chaining Deferreds</h1>
		<h2>Result from chaining from original deferred</h2>	
		<ul id="userlist1"></ul>
		<h2>Result from chaining from original.then()</h2>
		<ul id="userlist2"></ul>
		<h2>Result from chaining from original deferred after previous calls</h2>
		<ul id="userlist3"></ul>
		<!-- load dojo and provide config via data attribute -->
		<script src="dojo/dojo.js" data-dojo-config="isDebug: 1, async: 1, parseOnLoad: 1"></script>
		<script>
			require(["dojo/request", "dojo/_base/array", "dojo/json", "dojo/dom-construct", "dojo/dom", "dojo/domReady!"], function(request, arrayUtil, JSON, domConstruct, dom) {
				var original = request.get("users-mangled.json", {
					handleAs: "json"
				});	
				
				var result = original.then(function(res){
					var userlist = dom.byId("userlist1");
					console.log("以下代码用一维数组下标的方式,打印出res值");
					console.log(res[0]);
					console.log(res[1]);
					console.log(res[2]);	
					console.log("以上是用一维数组下标的方式,打印出res的值");

					//
					console.log("以下代码用二维数组下标的方式,打印出res值");
					console.log(res[0][0]);
					console.log(res[0][1]);
					console.log(res[0][2]);

					console.log(res[1][0]);
					console.log(res[1][1]);
					console.log(res[1][2]);

					console.log(res[2][0]);
					console.log(res[2][1]);
					console.log(res[2][2]);
					console.log("以上是用二维数组下标的方式,打印出res的值");

					return arrayUtil.map(res, function(user){
						domConstruct.create("li", {	innerHTML: JSON.stringify(user)}, userlist);
						console.log("以下代码用一维数组下标的方式,打印出user的值");
						console.log(user[0]);
						console.log(user[1]);
						console.log(user[2]);
						console.log("以上代码用一维数组下标的方式,打印出user的值");
						return {
							id: user[0],
							username: user[1],
							name: user[2]
						};
					});
				});
				    result.then(function(objs){
					var userlist = dom.byId("userlist2");
				console.log("以下代码用一维数组下标的方式,打印出objs的值");
				    console.log(objs[0]);
					console.log(objs[1]);
					console.log(objs[2]);	
				console.log("以上代码用一维数组下标的方式,打印出objs的值");
					//
					console.log("以下代码用二维数组下标的方式,打印出objs的值");
					console.log(objs[0][0]);
					console.log(objs[0][1]);
					console.log(objs[0][2]);
					console.log("以上是用二维数组下标的方式,打印出objs的值");
					console.log("实际运行会发现上面的打印结果是:undefine,即objs[][]是未定义的");

					arrayUtil.forEach(objs, function(user){
						domConstruct.create("li", {
							innerHTML: JSON.stringify(user)
						}, userlist);
					});
				});

				original.then(function(res){
					var userlist = dom.byId("userlist3");
				console.log("以下代码用一维数组下标的方式,再次打印出res的值");
				    console.log(res[0]);
					console.log(res[1]);
					console.log(res[2]);	
				console.log("以上代码用一维数组下标的方式,再次打印出res的值");
					//
					console.log("以下代码用二维数组下标的方式,再次打印出res的值");
					console.log(res[0][0]);
					console.log(res[0][1]);
					console.log(res[0][2]);

					console.log(res[1][0]);
					console.log(res[1][1]);
					console.log(res[1][2]);

					console.log(res[2][0]);
					console.log(res[2][1]);
					console.log(res[2][2]);
					console.log("以上是用二维数组下标的方式,再次打印出res的值");
					//console.log("实际运行会发现上面的打印结果是:undefine,即objs[][]是未定义的");

					arrayUtil.forEach(res, function(user){
						domConstruct.create("li", {
							innerHTML: JSON.stringify(user)
						}, userlist);
					});
				});

			});

		</script>
	</body>
</html>

下面是对上面代码的一点点解析。

先来看看

                    var result = original.then(function(res){
					var userlist = dom.byId("userlist1");
					console.log(res[0]);
					console.log(res[1]);
					console.log(res[2]);					

					return arrayUtil.map(res, function(user){
					domConstruct.create("li", {	innerHTML: JSON.stringify(user)}, userlist);
						console.log(user[0]);
						console.log(user[1]);
						console.log(user[2]);
						return {
							id: user[0],
							username: user[1],
							name: user[2]
						};
					});
				});

首先控制台打出:console.log(res[0]);console.log(res[1]);console.log(res[2]);

实际运行结果是:

如果修改console.log语句,让他打印出这个二维数组的值,看看是否可行?

代码段:

          console.log("以下代码用二维数组下标的方式,打印出res值");
					console.log(res[0][0]);
					console.log(res[0][1]);
					console.log(res[0][2]);

					console.log(res[1][0]);
					console.log(res[1][1]);
					console.log(res[1][2]);

					console.log(res[2][0]);
					console.log(res[2][1]);
					console.log(res[2][2]);
		   console.log("以上是用二维数组下标的方式,打印出res的值");

对应的 结果为:

所以现在就很清楚了,这个res就是一个二维数组,接下来的代码是对res用了一个 arrayUtil.map(res, function(user){},就是传入一个数组,即传入了res,对res数组的每个元素都调用了后面的函数,这个函数功能是:创建html 元素,赋予html 内容 ,然后返回的是最小粒度的数据user[0],user[1],user[2].同时前面还添加了id,username,name 字符串。

代码段:

return arrayUtil.map(res, function(user){
				domConstruct.create("li", {	innerHTML: JSON.stringify(user)}, userlist);
						console.log("以下代码用一维数组下标的方式,打印出user的值");
						console.log(user[0]);
						console.log(user[1]);
						console.log(user[2]);
						console.log("以上代码用一维数组下标的方式,打印出user的值");
						return {
							id: user[0],
							username: user[1],
							name: user[2]
						};
					});

结果:

 例子四:chaining的实际用法


<!DOCTYPE HTML>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Demo: Chaining Deferreds</title>

		<link rel="stylesheet" href="style.css" media="screen">
	</head>
	<body>
		<h1>Demo: Chaining Deferreds</h1>

		<ul id="userlist"></ul>

		<!-- load dojo and provide config via data attribute -->
		<script src="dojo/dojo.js" data-dojo-config="isDebug: 1, async: 1, parseOnLoad: 1"></script>
		<script>
			require(["dojo/request", "dojo/_base/array", "dojo/dom-construct", "dojo/dom", "dojo/domReady!"],
				function(request, arrayUtil, domConstruct, dom) {

					function getUserList(){
						return request.get("users-mangled.json", {
							handleAs: "json"
						}).then(function(response){
							return arrayUtil.map(response, function(user){
								return {
									id: user[0],
									username: user[1],
									name: user[2]
								};
							});
						});
					}

				getUserList().then(function(users){
					var userlist = dom.byId("userlist");
					arrayUtil.forEach(users, function(user){
						domConstruct.create("li", {
							id: user.id,
							innerHTML: user.username + ": " + user.name
						}, userlist);
					});
				});

			});

		</script>
	</body>
</html>

执行结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值