2016-12-30 77 views
1

我有点失落,我认为我击中了“不能看到树木综合征”。JavaScript/Node Promises:按顺序执行它们

Im a JS NooB和我试图了解如何调用一组JS函数(它返回承诺)按顺序。香港专业教育学院做了一些研读,并已决定使用即时通讯节点我应该使用类似蓝鸟管理承诺给予..

我不能工作了什么是为什么这段代码不工作

var Promise = require("bluebird"); 
// My Promise enabled function from oReily Safari book 
function countdown(seconds, timername) { 
    return new Promise(function (resolve, reject) { 
     console.log('Countdown : Starting Countdown ' + timername); 
     for (let i = seconds; i >= 0; i--) { 
      setTimeout(function() { 
       if (i > 0) 
        console.log(timername + ' ' + i + '...'); 
       else 
       { 
        console.log('countdown '+timername+' now=='+i+' resolving!'); 
        resolve(console.log("Countdown : timename="+timername+" ended")); 
       } 
      }, (seconds - i) * 1000); 
     } 
    }); 
} 

/*Basic test of promise */ 
/* when this is run I expected countdown(5, 'Basic : Timer1') to execute and then when **resolved** THEN countdown(5, "Basic Timer2") to execute. 
*however what I see is both timers executing at the same time.. 
*/ 

console.log('Basic : Countdown promise test'); 
countdown(5, 'Basic : Timer1'). 
     then(function() 
     { 
      /*Success */ 
      console.log("Basic : Ended Successfully"); 
     }). 
     then(countdown(5, "Basic : Timer2") 
       ); 

当我跑这我期待倒计时(5,“定时器1”)执行第一,然后,只有当定时器1完成后,将定时器得到执行..

然而,当我运行此我得到

Basic : Countdown promise test 
Countdown : Starting Countdown Basic : Timer1 
Countdown : Starting Countdown Basic : Timer2 
Basic : Timer1 5... 
Basic : Timer2 5... 
Basic : Timer1 4... 
Basic : Timer2 4... 
Basic : Timer1 3... 
Basic : Timer2 3... 
Basic : Timer1 2... 
Basic : Timer2 2... 
Basic : Timer1 1... 
Basic : Timer2 1... 
countdown Basic : Timer1 now==0 resolving! 
Countdown : timename=Basic : Timer1 ended 
countdown Basic : Timer2 now==0 resolving! 
Countdown : timename=Basic : Timer2 ended 
Basic : Ended Successfully 
Done. 

林失去了..

很多感谢

+0

你有一个小小的错字。 'then(countdow' should be'then(x => countdown())' –

回答

4

代码的最后一部分有一个意外的错误:

then(countdown(5, "Basic : Timer2")); 

这意味着倒计时的结果()作为回调函数。 (直接执行倒计时功能)

改用

then(function(lastResult){ countdown(5, "Basic : Timer2") }); 

可变lastResult将具有从该链中的较早承诺返回值。

+0

谢谢!特意感谢你解释为什么。我没有意识到参数“then”是一个回调函数,与函数调用本身.. – italianknows

1
console.log('Basic : Countdown promise test'); 
countdown(5, 'Basic : Timer1'). 
     then(function() 
      { 
       /*Success */ 
       console.log("Basic : Ended Successfully"); 
       return countdown(5, "Basic : Timer2"); 
      }). 
      then(function(){ 
       console.log("Finish!"); 
      }); 
0

你可以试试这个项目:https://github.com/LvChengbin/sequence

Sequence.all([ 
    () => countdown(5, 'Basic : Timer1'), 
    () => countdown(5, 'Basic : Timer2') 
]) 

你也可以使用Sequence.all方法的第二个参数指定两者interval每一个步骤。

您可以阅读其文档以获取更多信息。