How to correctly resolve a promise within promise constructor

倖福魔咒の 提交于 2021-01-29 08:50:30

问题


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 ?


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


来源:https://stackoverflow.com/questions/60408453/how-to-correctly-resolve-a-promise-within-promise-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!