async/await
function createLight(type, delay) {
return new Promise((resolve, reject) => {
console.log(type);
setTimeout(() => resolve(), delay * 1000);
});
}
const lights = [
createLight.bind(null, '红灯', 4),
createLight.bind(null, '黄灯', 2),
createLight.bind(null, '绿灯', 4)
];
async function start() {
while(true) {
for (const light of lights) {
await light();
}
}
}
start();
for...await...of
function createLight(type, delay) {
return new Promise((resolve, reject) => {
console.log(type);
setTimeout(() => resolve(type), delay * 1000);
});
}
async function* lightGenerator() {
const lights = [
createLight.bind(null, '红灯', 4),
createLight.bind(null, '黄灯', 2),
createLight.bind(null, '绿灯', 4)
];
for (const light of lights) {
yield light();
}
}
async function start() {
while(true) {
for await (const type of lightGenerator()) {
// console.log(type);
}
}
}
start();
展示
codepen