A, the title

Implement A function, sleep, that prints A first and B one second later.

Two, code implementation

Ideas:

  • Method 1: Implement it through Promise
  • Method 2: async/await
  • Method 3: Implement from Generator with yield

Methods a; Implementation through Promises

 console.log("A");
 function sleep(time) {
        return new Promise((resolve) = > {
          setTimeout(() = > {
            resolve();
          }, time);
        });
      }
      sleep(1000).then(() = > {
        console.log("B");
      });
Copy the code

Method 2: async/await

 console.log("A");
 function sleep2(time) {
        return new Promise((reslove, reject) = > {
          setTimeout(() = > {
            reslove();
          }, time);
        }).then(() = > {
          console.log("B");
        });
      }
      async function sleepAsync() {
        await sleep2(1000);
      }
      sleepAsync();
Copy the code

Method 3: Implement from Generator with yield

console.log("A");
const sleep = ((time) = >{
        return new Promise((resolive) = >{
          setTimeout(() = >{
            resolve();
          },time)
        })
      })

      function* sleepGenerator(time){
        yeild sleep(time);
      }

      sleepGenerator(1000).next().value.then(() = >{
        console.log("B");
      })
Copy the code