【问题标题】:How to correctly resolve a promise within promise constructor如何在 Promise 构造函数中正确解析 Promise
【发布时间】:2020-06-10 00:05:18
【问题描述】:
const setTimeoutProm = (delay) => new Promise(res => setTimeout(() => res(delay),delay))

我想做类似的事情,

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

这按预期工作,但我不确定这是否是正确的方法,或者有没有更好的方法?

【问题讨论】:

  • 为什么要使用asyncOper 函数?你不能用setTimeoutProm吗?

标签: javascript promise es6-promise


【解决方案1】:

不,实际上你这样做的方式是antipattern

你可以只从函数中返回一个承诺:

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

如果需要,也可以从 .then 内部返回 Promise:

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

或者也可以在异步函数中等待:

  async function asyncOpr(delay) {
    //...
    await setTimeoutProm(delay);
    //...
 }

【讨论】:

    猜你喜欢
    • 2023-01-18
    • 2020-05-23
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 2020-08-20
    • 2017-05-31
    • 2015-08-15
    • 1970-01-01
    相关资源
    最近更新 更多