html5 promise的使用
来源:互联网 发布:东北师大网络教育学院 编辑:程序博客网 时间:2024/04/29 10:14
promise的目的是减少callback的嵌套,提高代码的可维护性。看一个抽奖的例子,每次抽奖要1秒,共5次,生成一个1-10随机数,大于5则中奖。
<!DOCTYPE html><html><head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title></title></head><body> <script> function drawPrize(){ var defer = Promise.defer() setTimeout(function(){ var random = parseInt(Math.random() * 10); if(random>5){ defer.resolve({msg: 'gt 5', score: random}); }else{ defer.reject({msg: 'lte 5', score: random}); } },1000); return defer.promise; } for(var i=1;i<6;i++){ // drawPrize().then(function(data){ // console.log(data); // console.log('您中奖了'); // }).catch(function(data){ // console.log(data); // console.log('您未中奖'); // }); drawPrize().then(function(data){ console.log(data); console.log('您中奖了'); },function(data){ console.log(data); console.log('您未中奖'); }); } </script></body></html>
处理失败既可以放在catch中,也可以放在then的第二个参数。
Promise.defer()这种写法已经被一些新浏览器废弃,应使用new Promise()创建。
新代码:
<!DOCTYPE html><html><head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title></title></head><body> <script> function drawPrize(){ return new Promise(function(resolve,reject){ setTimeout(function(){ var random = parseInt(Math.random() * 10); if(random>5){ resolve({msg: 'gt 5', score: random}); }else{ reject({msg: 'lte 5', score: random}); } },1000); }); } for(var i=1;i<6;i++){ // drawPrize().then(function(data){ // console.log(data); // console.log('您中奖了'); // }).catch(function(data){ // console.log(data); // console.log('您未中奖'); // }); drawPrize().then(function(data){ console.log(data); console.log('您中奖了'); },function(data){ console.log(data); console.log('您未中奖'); }); } </script></body></html>
0 0
- html5 promise的使用
- 使用jQuery的Promise
- promise 的使用
- Promise的使用动机
- promise的简单使用
- es6 promise的使用
- Promise的使用
- ES6的Promise简单使用
- ECMAScript6标准Promise的使用
- Promise 、Async/Await的使用
- Promise对象的基本使用
- JavaScript中Promise的使用
- Asncy await Promise的使用
- Promise、Async/Await的使用
- 使用Promise/Deffered模式优化coco2d html5中的游戏动画!
- 使用Promise/Deffered模式优化coco2d html5中的游戏动画!
- JS的promise和extJS的promise的使用
- Promise使用
- 了解一个React组件
- Ionic基础——介绍及开发准备
- MyEclipse优化
- 房地产计算面积
- poj2935 Basic Wall Maze (2016xynu暑期集训检测 -----D题)
- html5 promise的使用
- Linux内存描述之内存节点node--Linux内存管理(二)
- 七、线性表(4)
- Java web项目中web.xml的配置
- git删除历史遗留大文件
- dexopt魔数验证
- [Codeforces Round #369 (Div. 2)D. Directed Roads]Tarjan强连通分量+组合计数
- 建议19:使用更有效的对象和集合初始化
- 十大算法展辉煌历史,十大问题引锦绣前程