首页 > 解决方案 > 停止执行进一步的代码

问题描述

我有个请求:

  Character.count({'character.ownerid': msg.author.id}, function (err, count) {
    if (err) {
      throw err;
    }

    if (count > 3) {
      err.message = 'Too many characters';
      //create error explanation and throw it
      throw err;
    }
  })

如果确实发生任何错误,我需要退出整个父函数。我不能在这个请求中返回,因为它只退出这个方法。我认为有可能进行如下回调:

Character.count({'character.ownerid': msg.author.id}, function (err, count, stop) {

但是如何使用它呢?它在一个匿名函数中,我不知道在哪里放置它的内容。我也尝试使用try/catch但由于 ,我无法向外部处理程序抛出错误Error: Unhandled "error" event. ([object Object]),请参见下面的代码:

Character.count({'character.ownerid': msg.author.id}, function (err, count) {
  if (err) {
    throw err;
  }

  if (count > 3) {
    var err = {};
    err.message = 'Too many characters';
    throw err;
  }
}).then((count) => {
  console.log('all good we may continue');
  console.log(count);
}).catch((err) => {
  if (err != undefined && err.length > 0) {
    msg.reply(err.message);
    return 0; //exit parent function?
  }
});

但即使这有效,我也不确定这段代码是否能满足我的需要。请求是异步的,那么如果其余代码之前被触发then怎么办?这甚至可能吗?

所以我基本上需要以return 0;某种方式访问​​父函数,如果有任何错误,我需要为它们提供处理程序。对此有什么想法吗?

标签: javascriptnode.jsmongodbmongoose

解决方案


你似乎错过了这个概念。首先,如前所述,所有 mongoose 操作都返回一个 Promise 或至少一个“类似 Promise”的对象,该对象可以立即通过 a 解决,then()而不是传入回调函数。这可以以两种方式呈现。

使用async/await语法和try..catch块:

const { Schema } = mongoose = require('mongoose');

const uri = 'mongodb://localhost/test';

mongoose.set('debug', true);
mongoose.Promise = global.Promise;

const characterSchema = new Schema({
  name: String
});

const Character = mongoose.model('Character', characterSchema);

const log = data => console.log(JSON.stringify(data,undefined,2));

const doCount = async () => {
  let count = await Character.count();

  if (count > 3)
    throw new Error("too many charaters");

  return count;

};


(async function() {

  try {
    const conn = await mongoose.connect(uri);

    await Promise.all(Object.entries(conn.models).map(([k,m]) => m.remove()))

    await Character.insertMany(
      ["Huey","Duey","Louie"].map(name => ({ name }))
    );

    let count = await doCount();
    log({ count });

    await Character.create({ name: 'Donald' });

    let newCount = await doCount();
    console.log("never get here");


  } catch(e) {
    console.error(e)
  } finally {
    mongoose.disconnect();
  }

})()

或者使用标准then()catch()语法:

const { Schema } = mongoose = require('mongoose');

const uri = 'mongodb://localhost/test';

mongoose.set('debug', true);
mongoose.Promise = global.Promise;

const characterSchema = new Schema({
  name: String
});

const Character = mongoose.model('Character', characterSchema);

const log = data => console.log(JSON.stringify(data,undefined,2));

function doCount() {
  return Character.count()
    .then(count =>  {

      if (count > 3)
        throw new Error("too many charaters");

      return count;
    });

};


(function() {

  mongoose.connect(uri)
    .then(conn => Promise.all(
      Object.entries(conn.models).map(([k,m]) => m.remove())
    ))
    .then(() => Character.insertMany(
      ["Huey","Duey","Louie"].map(name => ({ name }))
    ))
    .then(() => doCount())
    .then(count => log({ count }))
    .then(() => Character.create({ name: 'Donald' }))
    .then(() => doCount())
    .then(() => console.log("never get here"))
    .catch(e => console.error(e))
    .then(() => mongoose.disconnect() );

})()

两个清单的输出是一样的:

Mongoose: characters.remove({}, {})
Mongoose: characters.insertMany([ { _id: 5b0f66ec5580010efc5d0602, name: 'Huey', __v: 0 }, { _id: 5b0f66ec5580010efc5d0603, name: 'Duey', __v: 0 }, { _id: 5b0f66ec5580010efc5d0604, name: 'Louie', __v: 0 } ], {})
Mongoose: characters.count({}, {})
{
  "count": 3
}
Mongoose: characters.insertOne({ _id: ObjectId("5b0f66ec5580010efc5d0605"), name: 'Donald', __v: 0 })
Mongoose: characters.count({}, {})
Error: too many charaters
    at doCount (/home/projects/characters/index.js:20:11)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

As you can see the function happily returns it's value where the count remains 3 or under, but then throws an exception which stops further execution when the count would be greater than 3 since the "never get here" message never gets logged.

So there is no need for "callbacks" here and you would not use one unless you wrapped it in a Promise can did the same type of error handling anyway.

But if you have an "error" then throw the error. This works fine in a promise chain, but a "callback" which does not return as a Promise is simply not part of that chain and can never be "caught". So simply don't use the callback when you don't need to.

Just for kicks, wrapping a callback with a Promise would be done like:

function doCount() {
  return new Promise((resolve,reject) =>
    Character.count().exec((err,count) => {

      if (count > 3)
        reject(new Error("too many charaters"));

      resolve(count);
    })
  );
};

But it's noted not to be necessary considering the native methods return something you can resolve as a Promise anyway.


推荐阅读