我有一个请求:
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;
父函数,如果有任何错误,我需要为它们设置一个处理程序。有什么想法吗?
答案 0 :(得分:2)
你似乎错过了这个概念。首先,如前所述,所有的猫鼬行动都会返回一个承诺或至少一个承诺,就像#34;可以通过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)
正如你所看到的那样,函数很高兴地返回count
保持3或者不足的值,但是当count
大于3时,它会抛出一个异常停止进一步执行因为"never get here"
消息永远不会被记录。
因此不需要&#34;回调&#34;在这里你不会使用一个,除非你把它包装在一个Promise中,无论如何都可以做同样类型的错误处理。
但如果你有一个&#34;错误&#34;然后throw
错误。这在承诺链中工作正常,但是回调&#34;不作为承诺返回的东西根本不是该链的一部分,永远不会被抓住#34;因此,当您不需要时,请不要使用回调。
只是为了踢,用Promise包装一个回调就像:
function doCount() {
return new Promise((resolve,reject) =>
Character.count().exec((err,count) => {
if (count > 3)
reject(new Error("too many charaters"));
resolve(count);
})
);
};
但它注意到没有必要考虑到本机方法会返回一些你可以作为Promise解决的东西。