Search code examples
javascriptpromisees6-promise

How to correctly resolve a promise within promise constructor


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 ?


Solution

  • 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);
        //...
     }