利用 Promise 实现一个元素先红色两秒在黄色一秒再绿色三秒,不断循环。目前我想出的有三种方法。
首先是 HTML 代码:
     <table>
    <tbody>
        <tr>
            <td class="light"></td>
        </tr>
    </tbody>
</table>
1.第一种方法,这段代码其实只是利用了 setTimeout 的特性,只用 setTimeout 也可以实现。
let light = document.querySelector('.light');
function red() {
    return new Promise(function(resolve, reject) {
        light.style.backgroundColor = 'red';
        setTimeout(function() {
            resolve(green())
        }, 2000);
    })
}
function green() {
    return new Promise(function(resolve, reject) {
        light.style.backgroundColor = 'green';
        setTimeout(function() {
            resolve(yellow())
        }, 3000);
    })
}
function yellow() {
    return new Promise(function(resolve, reject) {
        light.style.backgroundColor = 'yellow';
        setTimeout(function() {
            resolve(red())
        }, 1000);
    })
}
red();
2.第二种方法,利用 Promise 和 async 函数的特性,是代码看起来更像是同步。
   let light = document.querySelector('.light');
   function lightChange(duration,color) {
    return new Promise(function(resolve,reject) {
        light.style.backgroundColor = color;
        setTimeout(resolve,duration);
    })
}
async function index() {
    while(1) {
        await lightChange(2000,'red');
        await lightChange(1000,'yellow');
        await lightChange(3000,'green');
    }
}
// async 函数提供了用同步代码编写异步的方式
index();
3.第三种方法用生成器和迭代器模拟 async 函数。这种写法并没有什么意义,只是写着玩,不推荐使用。
   let light = document.querySelector('.light');
   function func(color, duration) {
    return new Promise(function(resolve, reject) {
        light.style.backgroundColor = color;
        setTimeout(function() {
            it.next();
        }, duration)
    })
}
function* main() {
    while (1) {
        yield func('red',2000);
        yield func('yellow',1000);
        yield func('green',3000);
    }
}
var it = main();
it.next();

Gwen Weustink  2016-03-02 09-53-30 .jpg