代码如下所示:
const onRedLight = () => {console.log("red");
};const onGreenLight = () => {console.log("green");
};const onYellowLight = () => {console.log("yellow");
};const onLightUp = (timestamp, callback) => {return new Promise((resolve, reject) => {setTimeout(() => {callback?.();resolve();}, timestamp);});
};const onTrafficStep = () => {Promise.resolve().then(() => {return onLightUp(3000, onRedLight);}).then(() => {return onLightUp(2000, onGreenLight);}).then(() => {return onLightUp(1000, onYellowLight);}).then(() => {onTrafficStep(); // 执行完毕之后,递归执行});
};onTrafficStep();
效果如下图所示: