打破承诺链的好方法是什么

What is the good way to break from promise chain?

本文关键字:方法 是什么 承诺      更新时间:2023-09-26

我想知道如何正确地打破JS中的承诺链。

在这段代码中,我首先连接到数据库,然后检查集合是否已经有一些数据,如果没有添加的话。不要关注一些actionhero.js代码。。这在这里并不重要。

主要问题是:使用throw-null可以断链吗

mongoose.connect(api.config.mongo.connectionURL, {})
        .then(() => {
            return api.mongo.City.count();
        })
        .then(count => {
            if (count !== 0) {
                console.log(`Amout of cities is ${count}`);
                throw null; // break from chain method. Is it okay ?
            }
            return api.mongo.City.addCities(api.config.mongo.dataPath + '/cities.json');
        })
        .then(cities => {
            console.log("Cities has been added");
            console.log(cities);
            next();
        })
        .catch(err => {
            next(err);
        })

非常感谢!

尽管这看起来是一个聪明的技巧,而且会如您所期望的那样起作用,但我建议不要抛出非错误对象。

如果您抛出一个实际的错误并显式处理它,那么其他维护此代码的开发人员将更容易预测。

Promise
  .resolve()
  .then(() => {
    throw new Error('Already in database');
  })
  .catch(err => {
    if (err.message === 'Already in database') {
      // do nothing
    } else {
      next(err);
    }
  });