如何在Promise构造器中正确解析Promise [英] How to correctly resolve a promise within promise constructor

查看:60
本文介绍了如何在Promise构造器中正确解析Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这可以按预期工作,但是我不确定这是正确的方法还是有更好的方法?

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 ?

推荐答案

不,实际上您的操作方式是

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);
 };

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

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

这篇关于如何在Promise构造器中正确解析Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆