difference between 'util.promisify(setTimeout)' and 'ms => new Promise(resolve => setTimeout(resolve, ms))'

前端 未结 3 464
北荒
北荒 2021-01-21 11:47

Environment: node 8.11.x I want use async/await for sleep a while.

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
await sleep(5000)
         


        
3条回答
  •  春和景丽
    2021-01-21 11:50

    This can be a one-liner: await promisify(setTimeout)(1000).

    It works because setTimeout has a custom variant for promisify. It does work with node 8.11.

    nvm install 8.11 && nvm use 8.11
    node < {
        // const start = Date.now();
        await require('util').promisify(setTimeout)(5000);
        // console.log(Date.now() - start);
      })()
    HEREDOC
    

提交回复
热议问题