I have been coding in NodeJS from past 6 months but still, i don't have a clear picture about asynchronous and promise concept. Now coming to the question i will fetch a record using Mongoose from MongoDB which may have branchIds am performing a simple for loop in each iteration am performing a MongoDB operation which is asynchronous(as MongoDB/Mongoose operations are promises). As you know the for loop are synchronous but my function returns the value before the for loop ends. How does it happen? Am attaching the code if my question is not clear leave it as a comment.
const restManageChef = (params, query, body) => {
if (query && parseBoolean(query.superChef)) {
body = Object.assign(body, { role: 'SUPER-CHEF' });
} else {
body = Object.assign(body, { role: 'RES-CHEF' });
}
return restPUT(params, query, body).then(chef => {
return userModel
.findOne({ restaurantCode: chef.restaurantCode, type: 'RES-ADMIN' })
.then(resAdminDetails => {
log.debug({ Chef: chef }, 'Chef Details');
if (chef.role === 'SUPER-CHEF') {
log.debug({ BranchIds: resAdminDetails.branchIds }, 'BranchIds');
for (let i = 0; i < resAdminDetails.branchIds.length; i) {
log.debug({ BranchIds: resAdminDetails.branchIds[i] }, 'BranchIds');
pushChefId(resAdminDetails.branchIds[i], chef.pkid)
.then(restaurant => {
log.debug({ Restaurant: restaurant }, 'Restaurant Details');
})
.catch(err => {
log.error({ err });
throw err;
});
}
return chef;
} else if (chef.role === 'RES-CHEF') {
for (let i = 0; i < resAdminDetails.branchIds.length; i++) {
log.debug({ BranchIds: resAdminDetails.branchIds[i] }, 'BranchIds');
pushChefId(resAdminDetails.branchIds[i], chef.pkid)
.then(restaurant => {
log.debug({ Restaurant: restaurant }, 'Restaurant Details');
})
.catch(err => {
log.error({ err });
throw err;
});
}
return chef;
}
});
});
};
PushChefId Function
const pushChefId = (restaurantCode, chefId) => {
return userModel
.findOneAndUpdate({ restaurantCode }, { $addToSet: { chefIds: chefId } })
.exec()
.then(resAdmin => {
if (!resAdmin) return Promise.reject(`No RES-ADMIN found with restaurantCode - ${restaurantCode}`);
return storeModel.findByIdAndUpdate(restaurantCode, { $addToSet: { chefIds: chefId } }, { new: true });
});
};