0

It's year 2018 and modem node is of version 9 or 10, i.e., the accepted answer from How Can I Wait In Node.js in year 2013 is no good any more. Hence I'm asking it again, as per the guidance of meta here.

The criteria for the answer now is to use existing ES6 and Node.js v9+ features without any extra packages.

I found the answer from @treecoder at https://stackoverflow.com/a/44036791/2125837 particular interesting, but I just can't make it work for my case:

$ node
> const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

> const waitThenDo = async (howLong, doWhat) => await sleep(howLong*1000).then(doWhat)

> waitThenDo(1, console.log(2))
2
Promise {
  <pending>,
 ... 

I.e., the waitThenDo does the printing right away, without any delay.

What I've done wrong, and/or, what the best latest technology to wait/sleep?

xpt
  • 13,224
  • 19
  • 76
  • 149
  • Just FYI: The @ notation to ping someone only works if they have written an answer or comment to this specific question. You can't just reach out and touch someone at random here; this isn't a chatroom or social networking site. It's also inappropriate to address your question to a single person. If you want to personalize your questions, hire a contractor that you can correspond with directly. – Ken White Feb 20 '18 at 17:47
  • ok. thanks for the kind explanation. – xpt Feb 20 '18 at 17:48
  • `doWhat` needs to be a callback *function*. – Bergi Feb 20 '18 at 18:27
  • Try `async function waitAndLog() { await sleep(1000); console.log(2); }` – Bergi Feb 20 '18 at 18:28

1 Answers1

1

The then method of a promise expects a function:

waitThenDo(1, () => console.log(2))

You could also do this:

const waitThenDo = async (howLong, doWhat) => {
  await sleep(howLong*1000)
  doWhat()
}

waitThenDo(1, () => console.log(2))
Steve Holgado
  • 8,378
  • 2
  • 16
  • 22