简体   繁体   English

为什么这个诺言行不通?

[英]Why this promise does not work?

I'm playing with Promise. 我在玩Promise。

This is my code : 这是我的代码:

APC.UTIL.AutoDOM = {
   step: -1,  PROMISES : [],          
   add: function (fun) {      
    this.PROMISES.push (fun);

  },          
  run: function () {      
   this.step = 0;   this.nn   = this.PROMISES.length-1; 
   this.PROMISES.push ( function() {this.end();});      

    Promise.all( this.PROMISES).then (   
     function ( ) { APC.UTIL.AutoDOM.step++; console.log("OK"+APC.UTIL.AutoDOM.step);}   
     ).catch(
     function(err) {    console.log(err);}
     ); 
  },
  end: function () {
     this.PROMISES.clear();


  }                  
  }

And used so : 并这样使用:

 APC.UTIL.AutoDOM.add (  function () {console.log("hello1");}   );        
 APC.UTIL.AutoDOM.add (  function () {console.log("hello2");}   );      
 APC.UTIL.AutoDOM.add (  function () {console.log("hello3");}   );      

 APC.UTIL.AutoDOM.run(); 

Only works one time.... 只工作一次。

OK1 OK1

Anybody can fix my code ? 有人可以修复我的代码吗? TH TH

What you have here in PROMISES isn't an array of promises but an array of functions. 您在PROMISES中拥有的不是承诺,而是功能。 If your goal is to have all those functions executed (possibly in parallel) then to have another function executed with the result of each one, you can do this : 如果您的目标是要执行所有这些功能(可能是并行执行),然后执行另一个功能且每个功能的结果相同,则可以执行以下操作:

Promise
.map(this.PROMISES, function(f){ f() })
.map(function(_, i){ console.log('OK'+(i+1)) })
.finally(function(){ this.PROMISES.clear(); });

Disclaimer : tested with Bluebird 免责声明:已通过Bluebird测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM