如何解决NodeJS方法优先级问题



在这种情况下,方法3首先工作,我得到了错误。它的优先级必须类似于方法1、方法2和方法3。这些方法是承诺吗?并且承诺以异步方式工作。

我想检查新用户的用户名和电子邮件是否在使用中。如果用户名或电子邮件未被使用,请注册。

我该如何解决这个问题?我是nodejs的新手。

module.exports.addUser = function(newUser, callback) {
// method 1
User.countDocuments({username: newUser.username}).then(count => {
if(count > 0) {
console.log("username in use");
callback("username in use", null);
return;
}});
// method 2
User.countDocuments({email: newUser.email}).then(count => {
if(count > 0) {
console.log("email in use");
callback("email in use", null);
return;
}});
// method 3 , this method works first
bcrypt.genSalt(10, (err, salt) => {
console.log("salt here");
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err) throw err;
newUser.password = hash;
newUser.save(callback);
});
});
};

输出:

salt here
username in use
email in use
(node:7972) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (C:UserscycloneDesktopmy_authnode_modulesexpresslibresponse.js:767:10)
at ServerResponse.send (C:UserscycloneDesktopmy_authnode_modulesexpresslibresponse.js:170:12)
at ServerResponse.json (C:UserscycloneDesktopmy_authnode_modulesexpresslibresponse.js:267:15)
at User.addUser (C:UserscycloneDesktopmy_authroutesusers.js:20:17)
at User.countDocuments.then.count (C:UserscycloneDesktopmy_authmodelsuser.js:48:13)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:189:7)
(node:7972) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:7972) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled
will terminate the Node.js process with a non-zero exit code.
events.js:183
throw er; // Unhandled 'error' event
^
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (C:UserscycloneDesktopmy_authnode_modulesexpresslibresponse.js:767:10)
at ServerResponse.send (C:UserscycloneDesktopmy_authnode_modulesexpresslibresponse.js:170:12)
at ServerResponse.json (C:UserscycloneDesktopmy_authnode_modulesexpresslibresponse.js:267:15)
at User.addUser (C:UserscycloneDesktopmy_authroutesusers.js:22:17)
at C:UserscycloneDesktopmy_authnode_modulesmongooselibmodel.js:4518:16
at model.$__save.error (C:UserscycloneDesktopmy_authnode_modulesmongooselibmodel.js:422:7)
at C:UserscycloneDesktopmy_authnode_moduleskareemindex.js:315:21
at next (C:UserscycloneDesktopmy_authnode_moduleskareemindex.js:209:27)
at C:UserscycloneDesktopmy_authnode_moduleskareemindex.js:182:9
at process.nextTick (C:UserscycloneDesktopmy_authnode_moduleskareemindex.js:499:38)
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickCallback (internal/process/next_tick.js:181:9)
[nodemon] app crashed - waiting for file changes before starting...

countDocuments之后使用"then"这一事实表明它是一个promise,因此是异步的。

此时最简单的解决方案是将addUser函数定义为async

module.exports.addUser = async function(newUser, callback) {
// method 1
const count1 = await User.countDocuments({
username: newUser.username
});
if (count1 > 0) {
console.log("username in use");
callback("username in use", null);
return;
};
// method 2
const count2 = await User.countDocuments({
email: newUser.email
});
if (count2 > 0) {
console.log("email in use");
callback("email in use", null);
return;
};
// method 3 , this method works first
bcrypt.genSalt(10, (err, salt) => {
console.log("salt here");
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser.save(callback);
});
});
};

然而,现在为addUser设置回调函数是毫无意义的,因为异步函数会自动返回promise。我建议你这样做…

module.exports.addUser = async function(newUser) {
// method 1
const count1 = await User.countDocuments({
username: newUser.username
});
if (count1 > 0) {
throw Error("username is in use");
};
// method 2
const count2 = await User.countDocuments({
email: newUser.email
});
if (count2 > 0) {
throw Error("email in use");
};
let result = null;
// method 3 , this method works first
bcrypt.genSalt(10, (err, salt) => {
console.log("salt here");
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
result = await newUser.save(callback);
});
});
return result;
};

在使用中,它看起来像:

addUser(someUserObject).then(result=>console.log(result)).catch(error=>{
//Example: username in use
console.log(error.message)
});

最新更新