題目:紅燈三秒亮一次,綠燈一秒亮一次,黃燈2秒亮一次;如何讓三個燈不斷交替重複亮燈?(用Promise實現)html
解答思路一:spa
function red(){ console.log('red'); } function green(){ console.log('green'); } function yellow(){ console.log('yellow'); } var tic = function(timmer, cb){ return new Promise(function(resolve, reject) { setTimeout(function() { cb(); resolve(); }, timmer); }); }; var d = new Promise(function(resolve, reject){resolve();}); var step = function(def) { def.then(function(){ return tic(3000, red); }).then(function(){ return tic(2000, green); }).then(function(){ return tic(1000, yellow); }).then(function(){ step(def); }); } step(d);
解答思路二:code
// 方法二:雖然Promise能夠用來解決回調地獄問題,可是仍然不可避免的會有回調出現 var tic = function(timmer, str){ return new Promise(function(resolve, reject) { setTimeout(function() { console.log(str); resolve(1); }, timmer); }); }; function *gen(){ yield tic(3000, 'red'); yield tic(1000, 'green'); yield tic(2000, 'yellow'); } var iterator = gen(); var step = function(gen, iterator){ var s = iterator.next(); if (s.done) { step(gen, gen()); } else { s.value.then(function() { step(gen, iterator); }); } } step(gen, iterator);
摘錄來源:http://www.cnblogs.com/dojo-lzz/p/5495671.htmlhtm