File tree Expand file tree Collapse file tree 1 file changed +26
-8
lines changed Expand file tree Collapse file tree 1 file changed +26
-8
lines changed Original file line number Diff line number Diff line change @@ -116,34 +116,52 @@ userSchema.pre('save', function checkPassword(next) {
116116 * API keys hash middleware
117117 */
118118userSchema . pre ( 'save' , function checkApiKey ( next ) {
119- // eslint-disable-line consistent-return
120119 const user = this ;
121120 if ( ! user . isModified ( 'apiKeys' ) ) {
122121 next ( ) ;
123122 return ;
124123 }
124+
125125 let hasNew = false ;
126+ let pendingTasks = 0 ;
127+ let nextCalled = false ;
128+
129+ const done = ( err ) => {
130+ if ( nextCalled ) return ;
131+ if ( err ) {
132+ nextCalled = true ;
133+ next ( err ) ;
134+ return ;
135+ }
136+ pendingTasks -= 1 ;
137+ if ( pendingTasks === 0 ) {
138+ nextCalled = true ;
139+ next ( ) ;
140+ }
141+ } ;
142+
126143 user . apiKeys . forEach ( ( k ) => {
127144 if ( k . isNew ) {
128145 hasNew = true ;
146+ pendingTasks += 1 ;
129147 bcrypt . genSalt ( 10 , ( err , salt ) => {
130- // eslint-disable-line consistent-return
131148 if ( err ) {
132- next ( err ) ;
133- return ;
149+ done ( err ) ;
134150 }
135151 bcrypt . hash ( k . hashedKey , salt , ( innerErr , hash ) => {
136152 if ( innerErr ) {
137- next ( innerErr ) ;
138- return ;
153+ done ( innerErr ) ;
139154 }
140155 k . hashedKey = hash ;
141- next ( ) ;
156+ done ( ) ;
142157 } ) ;
143158 } ) ;
144159 }
145160 } ) ;
146- if ( ! hasNew ) next ( ) ;
161+
162+ if ( ! hasNew ) {
163+ next ( ) ;
164+ }
147165} ) ;
148166
149167userSchema . virtual ( 'id' ) . get ( function idToString ( ) {
You can’t perform that action at this time.
0 commit comments