Combination of async function + await + setTimeout

前端 未结 12 1523
予麋鹿
予麋鹿 2020-11-22 04:34

I am trying to use the new async features and I hope solving my problem will help others in the future. This is my code which is working:

  async function as         


        
12条回答
  •  無奈伤痛
    2020-11-22 05:14

    Since Node 7.6, you can combine the functions promisify function from the utils module with setTimeout() .

    Node.js

    const sleep = require('util').promisify(setTimeout)
    

    Javascript

    const sleep = m => new Promise(r => setTimeout(r, m))
    

    Usage

    (async () => {
        console.time("Slept for")
        await sleep(3000)
        console.timeEnd("Slept for")
    })()
    

提交回复
热议问题