js promise 中使用 setTimeout 实现暂停执行

发布时间 2023-04-21 15:02:50作者: aganjue

在使用 promise 时,需要使用 setTimeout 来进行延时执行

promise 还不太熟悉的同学可能第一时间想到的是这样的写法

如:

run();

async function run() {

      console.log('1');
      
      // 等待两秒之后执行
      setTimeout(() => {

          const data = await getData();

          console.log(data);
          
      }, 200);
      
  }

function getData() {

      return new Promise((resolve, reject) => {

          resolve("200");
          
      })
      
}

这样写 await 就报错了

想要实现延时效果,我们这里先封装个sleep

 function x_sleep(time) {

        return new Promise(resovle => {

            setTimeout(() => {

                resolve();
                
            }, time)
            
        })
        
 }

此时就可以通过我们的 sleep函数去进行延时处理了

完整代码:

    run();

    async function run() {

        console.log("1");

        // 停止2秒
        await x_sleep(2000);

        const data = await getData();

        console.log(data);
        
    }

    function getData() {

        return new Promise((resolve, reject) => {

            resolve("200");
            
        })
        
    }

    function x_sleep(time) {

        return new Promise(resolve => {

            setTimeout(() => {

                resolve();
                
            }, time)
            
        })
        
    }