1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var asyncTask = eval(Wind.compile("async", function (idx) { // 运行“编译”后的代码', 得到句柄 for (var i=0; i<5; i++) { $await(Wind.Async.sleep(2000)); // 等待2秒再继续执行 var result = parseInt(Math.random() * 100, 10) % 2, time = (new Date()).getTime(), prefix = "Wind.js " + time + " " + i + ":"; if (result == 0) { console.info(prefix + "got an even number"); } else { console.info(prefix + "got an odd number"); } } })); asyncTask().start(); // 开始运行异步任务 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | Employee.all = function(opt) { var opt = opt || {local: true}, Task = Wind.Async.Task; if (opt.local === true) { throw new Error('not implemented!'); } else { return Task.create(function(t) { // 创建 Wind.Async.Task实例, 封装必须使用回调方法的代码 $.ajax({ url: "/async/api/employee", dataType: "json" }).then(function(items) { var employees = []; $(items).each(function(idx, item) { employees.push(new Employee(item)) }); t.complete("success", employees); // 操作成功 }, function(err) { t.complete("failure", err); // 操作失败 }); }); } }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | $(document).ready(function() { var employeeTask = eval(Wind.compile("async", function (idx) { // 生成句柄 try { var employees = $await(Employee.all({local: false})); // 通过$await方法以便”编译” for (var i=0; i<employees.length; i++) { var employee = employees; if (employee.age >= 30) { var employeeWithDetail = $await(Employee.get(employee.id, {local: false})); $await(employeeWithDetail.create({local: true})); } else { $await(employee.create({local: true})); } } } catch(err) { console.error(err); } })); employeeTask().start(); }); }); |
1 2 3 4 5 6 7 8 9 10 11 12 | Deferred.define(); // 将JSDeferred的方法变成全局方法 loop(5, function (i) { // 顺序循环5次 var result = parseInt(Math.random() * 100, 10) % 2, time = (new Date()).getTime(), prefix = "JSDeferred " + time + " " + i + ":"; if (result == 0) { console.info(prefix + "got an even number"); } else { console.info(prefix + "got an odd number"); } return wait(2); // 等待2秒 }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | $(document).ready(function() { Deferred.define(); next(function () { return Employee.all({local: false}); // 当从远端获得所有员工数据时,才运行下一步 }). next(function (employees) { return loop(employees.length, function(i) { // 顺序遍历员工 var employee = employees; if (employee.age >= 30) { return Employee.get(employee.id, {local: false}) .next(function(employeeWithDetail) { return employeeWithDetail.create({local: true}); }); // 从远端获取员工明细,保存到本地 } else { return employee.create({local: true}); } }) }). error(function(err) { console.error(err); // 异常会导致异步过程中断,并被打印 }) }); |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |