demo2.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. var Queue = require('../');
  2. var q = Queue.Q; //内置的Promise,仿Q的API
  3. //定义一些方法
  4. function workResolve(data,obj){
  5. console.log('第' + data + '事件完成 - 运行中事件数:' + this.getRunCount() + ' - 剩余:' + this.getLength())
  6. }
  7. function workReject(err,obj){
  8. console.log('一个执行单元状态拒绝' + err)
  9. }
  10. function queueStart(){
  11. console.log('>>>>>> 队列开始')
  12. }
  13. function queueEnd(){
  14. console.log('<<<<<< 队列结束了')
  15. }
  16. function workFinally(){
  17. console.log('一个执行单元完成')
  18. }
  19. function workAdd(){
  20. console.log("向队列添加项 ",this.isStart(),this.getLength())
  21. if(!this.isStart() && this.getLength() >= 5){ //当添加了10个项后,运行队列
  22. console.log(">> 触发自动运行条件")
  23. this.start();
  24. }
  25. }
  26. // var q1 = new Queue(1)
  27. // q1.push(function(){return "123"}).then(console.log,console.log);
  28. // q1.start();
  29. //new Queue([并行数],<options>) 并行数必须
  30. var queue1 = new Queue(2,{
  31. "queueStart": queueStart
  32. ,"queueEnd": queueEnd
  33. ,"workResolve": workResolve
  34. ,"workReject": workReject
  35. ,"workFinally": workFinally
  36. ,"retry":0 //出错重试次数 默认0;
  37. ,'workAdd':workAdd //workAdd只会在push/unshift方法添向项时才触发!
  38. })
  39. function testfun(i){
  40. var deferred = q.defer();
  41. setTimeout(function(){
  42. if(i%3 == 1 || i == "Qerr"){
  43. deferred.reject(new Error("err is " + i))
  44. }else{
  45. deferred.resolve(i)
  46. }
  47. },1000)
  48. return deferred.promise;
  49. }
  50. //用push添加项 不会启动队列;
  51. queue1.push(testfun,['Q1'])
  52. queue1.addLikeArrayEach([1,2,3,4,5],function(v,i,arr){
  53. var deferred = q.defer();
  54. setTimeout(function(){
  55. deferred.resolve(i+":"+v);
  56. },500);
  57. return deferred.promise;
  58. },0,1).then(function(data){
  59. console.log(data);
  60. })
  61. setTimeout(function(){
  62. //用go添加项 将会启动队列;
  63. queue1.go(testfun,['Q2'])
  64. //添加的项返回的是一个promise,所以可以在添加时就定义好“回调”
  65. queue1.go(testfun,['Q3']).then(console.log,console.log) //succ
  66. queue1.go(testfun,['Qerr']).then(console.log,console.log) //err
  67. //也可以这样添加“回调”
  68. var con = {
  69. 'workResolve':function(data){
  70. console.log(data + '完成!')
  71. }
  72. ,'workReject':function(err){
  73. console.error(err)
  74. }
  75. }
  76. queue1.go(testfun,['Q4'],con)
  77. //标记此对象不会走队列的成功失败事件.
  78. queue1.go(testfun,['Q5'],{run_queue_event:false}).then(function(data){console.log(data + "不会触发队列初始化时定义的成功/失败方法")})
  79. },0)