在承诺中包含一个反模式的承诺吗? [英] Is wrapping a promise in a promise an anti-pattern?

查看:45
本文介绍了在承诺中包含一个反模式的承诺吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Promise API编写重新连接到数据库的代码,并使用Promise API进行超时。



我最终做的是将承诺包装到在承诺中连接到DB,但我不确定这是否是最好的做事方式。我认为可能有一种方法可以使用原始承诺来尝试连接到数据库,但我无法弄明白。

  function connect(resolve){
console.log('Connecting to db ...');
MongoClient.connect(url,{promiseLibrary:Promise})
.then((db)=> resolve(db))
.catch((err)=> {
console.log('db connection failed!:\ n',err);
if(retry ++< 3){
console.log('再试一次......');
setTimeout(()=> connect(resolve),5000);
} else {
console.log('达到重试限制!');
}
});
}

module.exports = new Promise(connect);

我认为没有 setTimeout 阻止,但我无法解决它。

解决方案

这是一个稍微更通用的解决方案:

  function withRetry(asyncAction,retries){
if(retries === 0){
// Promise.resolve to conversion同步引发拒绝。
返回Promise.resolve()。then(asyncAction);
}
返回Promise.resolve()
.then(asyncAction)
.catch(()=> withRetry(asyncAction,retries - 1));
}

此函数将采用一个函数返回一个promise和多次重试,如果Promise拒绝,则重试该函数的次数为 retries



如果它结算,则重试在你的情况下:

 让connectionPromise = withRetry (连接,3); //如果失败则连接3次重试


I was trying to write code for reconnecting to a database with a timeout using a Promise API.

What I ended up doing in the end was wrapping the promise to connect to the DB in a promise, but I'm not sure if that's the best way to do things. I thought there might be a way to use the original promise from trying to connect to the db, but I couldn't figure it out.

function connect(resolve) {
  console.log('Connecting to db...');
  MongoClient.connect(url, { promiseLibrary: Promise })
    .then((db) => resolve(db))
    .catch((err) => {
      console.log('db connection failed!:\n', err);
      if (retry++ < 3) {
        console.log('Trying again...');
        setTimeout(() => connect(resolve), 5000);
      } else {
        console.log('Retry limit reached!');
      }
    });
}

module.exports = new Promise(connect);

I think it would be possible without the setTimeout block, but I couldn't work around it.

解决方案

Here's a slightly more general solution:

function withRetry(asyncAction, retries) {
  if (retries === 0) {
    // Promise.resolve to convert sync throws into rejections.
    return Promise.resolve().then(asyncAction); 
  }
  return Promise.resolve()
    .then(asyncAction)
    .catch(() => withRetry(asyncAction, retries - 1));
}

This function will take a function that returns a promise, and a number of retries, and retry the function as many times as retries, if the Promise rejects.

If it resolves, the retry chains stops.

In your case:

let connectionPromise = withRetry(connect, 3); // connect with 3 retries if fails.

这篇关于在承诺中包含一个反模式的承诺吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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