我想知道如何在JS中正确打破Promise链。

在这段代码中,我首先连接到数据库,然后检查集合是否已经有一些数据,如果没有添加它们。不要注意一些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);
        })


非常感谢!

最佳答案

尽管它看起来像是一个巧妙的技巧,并且可以按您期望的那样工作,但我还是建议您不要抛出非错误对象。

如果您抛出一个实际的Error并明确地处理它,那么其他维护该代码的开发人员将更容易预测。

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

关于javascript - 打破 promise 链的好方法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37296877/

10-12 12:33