红绿灯任务控制

  1. function red(){
  2. console.log('red')
  3. }
  4. function yellow(){
  5. console.log('yellow')
  6. }
  7. function green(){
  8. console.log('green')
  9. }
  10. const task = (timer, light) => {
  11. return new Promise((resolve, reject) => {
  12. setTimeout(() => {
  13. if(light === 'red'){
  14. red()
  15. }else if (light === 'yellow'){
  16. yellow()
  17. }else if (light === 'green'){
  18. green()
  19. }
  20. resolve()
  21. }, timer)
  22. })
  23. }
  24. // promise
  25. const step = () => {
  26. task(3000, 'red').then(() => {
  27. task(1000, 'yellow')
  28. }).then(() => {
  29. task(2000, 'green')
  30. }).then(step)
  31. }
  32. step()
  33. // async、await
  34. const step = async () => {
  35. await task(3000, 'red')
  36. await task(1000, 'yellow')
  37. await task(2000, 'green')
  38. step()
  39. }
  40. step()