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

前端 未结 3 451
北荒
北荒 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 <<HEREDOC
      (async () => {
        // const start = Date.now();
        await require('util').promisify(setTimeout)(5000);
        // console.log(Date.now() - start);
      })()
    HEREDOC
    
    0 讨论(0)
  • 2021-01-21 12:08

    promisify is expects a function that has final argument that is the callback.

    In other a words it wants a function that looks like:

    function takesACallback(str, Fn) {
        Fn(null, "got: ", str)
        // or with an error:
        // Fn(error)
    }
    

    Of course setTimout is the opposite. The argument you want to pass in is the last argument. So when you try to call the promisifyd function and pass in an argument, it will take that argument -- the delay-- and try to call it like a function. Of course that's an error.

    For entertainment (and slight educational) purposes only, you can pass in a function that reverses the arguments and it will work:

    let util = require('util')
    
    let pause = util.promisify((a, f) => setTimeout(f, a))
    pause(2000)
    .then(() => console.log("done"))
    

    Now the final argument of the function you passed to promisify expects function. But the asyn/await method is so much nicer…

    0 讨论(0)
  • 2021-01-21 12:13

    You know that this right here works:

    const {promisify} = require('util');
    const sleep = promisify(setTimeout);
    
    ;(async () => {
    
      const ts = Date.now()
    
      await sleep(5000)
    
      console.log(Date.now()-ts)
    
    })();
    

    This works fine, why not go with it and use it???

    0 讨论(0)
提交回复
热议问题