在应用程序启动脚本中使用asynchronous不会返回任何结果

我正尝试在Node应用程序中运行以下脚本来检查是否存在任何用户,如果不存在,请创build第一个pipe理用户。 然而剧本什么也不做,甚至在使用Try / Catch的时候什么都不返回,所以有人能告诉我我在这里错过了什么? 或者我怎么可能赶上错误(如果有的话)? 谢谢

import pmongo from 'promised-mongo'; import crypto from 'crypto'; const salt = 'DuCDuUR8yvttLU7Cc4'; const MONGODB_URI = 'mongodb://localhost:27017/mydb'; const db = pmongo(MONGODB_URI, { authMechanism: 'ScramSHA1' }, ['users']); async function firstRunCheckAndCreateSuperAdmin(cb) { const username = 'admin2@test2.com'; try { const user = await db.users.findOne({ role: 'admin'}); console.log(user); if(!user) return cb('No user found'); } catch(e) { cb('Unexpected error occurred'); } if(!user) { console.log('No admin detected.'); const adminPassword = crypto.pbkdf2Sync ( 'password', salt, 10000, 512, 'sha512' ).toString ( 'hex' ); await db.users.update({username: username}, {$set: {username: username, password: adminPassword, role: 'admin'}}, {upsert: true}); } db.close(); process.exit(); } firstRunCheckAndCreateSuperAdmin(function(err, resultA){ if(err) console.log(err); }); 

在下面的代码片段中没有pipe理员用户时,您不会返回任何callback

 if (!user) { console.log('No admin detected.'); const adminPassword = crypto.pbkdf2Sync ( 'password', salt, 10000, 512, 'sha512' ).toString ( 'hex' ); await db.users.update({username: username}, {$set: {username: username, password: adminPassword, role: 'admin'}}, {upsert: true}); // call cb(user) here } 

请参阅评论。

 import pmongo from 'promised-mongo'; import crypto from 'crypto'; const salt = 'DuCDuUR8yvttLU7Cc4'; const MONGODB_URI = 'mongodb://localhost:27017/mydb'; const db = pmongo(MONGODB_URI, { authMechanism: 'ScramSHA1' }, ['users']); async function firstRunCheckAndCreateSuperAdmin(cb) { const username = 'admin2@test2.com'; try { const user = await db.users.findOne({ role: 'admin' }); console.log(user); //(1) If user is undefined, then launch cb with an error message; if (!user) return cb('No user found'); } catch (e) { //(2) If something is wrong, then launch cb with an error message; cb('Unexpected error occurred'); } //This part of the code will only be reached if user is defined. //This is a dead code as if user is undefined, it would have exited at (1) if (!user) { console.log('No admin detected.'); const adminPassword = crypto.pbkdf2Sync('password', salt, 10000, 512, 'sha512').toString('hex'); await db.users.update({ username: username }, { $set: { username: username, password: adminPassword, role: 'admin' } }, { upsert: true }); } //So if user exists, it will close db and exit without calling cb. db.close(); process.exit(); } firstRunCheckAndCreateSuperAdmin(function(err, resultA) { if (err) console.log(err); }); 

注意:

  • 如果你正在使用asynchronous/等待,那么你不需要使用callback。
  • 如果您使用callback,则不需要返回语句。
  • 如果函数的意图是假设有一个返回值,确保所有的代码path返回一个值。

我试图重写你的代码,使其更小,并从中删除所有节点式的callbacktypes的asynchronous代码。 我用insertOnereplace了update ,因为你只有一个用户插入(不是多个更新)。 另外,我在调用firstRunCheckAndCreateSuperAdmin以防“挂起”的情况下增加了500毫秒的超时时间。 它应该logging的东西:)

 import pmongo from 'promised-mongo' import crypto from 'crypto' import { promisify } from 'util' const pbkdf2 = promisify(crypto.pbkdf2) const salt = 'DuCDuUR8yvttLU7Cc4' const MONGODB_URI = 'mongodb://localhost:27017/mydb' const db = pmongo(MONGODB_URI, { authMechanism: 'ScramSHA1' }, ['users']); const username = 'admin2@test2.com' async function firstRunCheckAndCreateSuperAdmin() { let user = await db.users.findOne({ role: 'admin' }); if (!user) { // no user lets create one user = await db.users.insertOne({ username: username, password: (await pbkdf2('password', salt, 10000, 512, 'sha512')).toString('HEX'), role: 'admin' }); } return user } const timeout = delay => message => new Promise((_, reject) => setTimeout(reject, delay, new Error(message))) Promise .race([firstRunCheckAndCreateSuperAdmin(), timeout(500)('Rejected due to timeout')]) .then(user => console.log(`Got user ${JSON.stringify(user)}`)) .catch(error => console.error(error))