0
const setTimeoutProm = (delay) => new Promise(res => setTimeout(() => res(delay),delay))

I want to do something like,

const asyncOpr = (delay) => { 
  return new Promise((resolve, reject) => { 
    //update delay for some reason.
    const updatedDelay = delay * 2;
    setTimeoutProm(updatedDelay).then(res => {
      resolve(res);
    }).catch(err => {})
  })
}
asyncOpr(2000).then(() => alert("resolved")) //this works

This works as expected, but I am not sure if this is correct way of doing this or is there any better way of doing this ?

laxman
  • 1,781
  • 4
  • 14
  • 32

1 Answers1

1

No, actually the way you do it is an antipattern.

You can just return a promise from the function:

 const asyncOpr = (delay) => { 
  return setTimeoutProm(delay);
 };

If needed, a Promise could also be returned from inside a .then:

 doA()
   .then(() => setTineoutProm(1000))
   .then(() => doB());

Or it can also be awaited inside an async function:

  async function asyncOpr(delay) {
    //...
    await setTimeoutProm(delay);
    //...
 }
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151