函数返回null,等待结果未应用



我在post方法中使用以下函数。使用了async await,但在transferAmount totalBalance中,当我调用post路由内的函数时,它不会更新。函数的返回不正确。我需要指导,以便它返回具有更新值的对象。

async function transferAmount(fromAccountId, toAccountId, amount) {
const session = await mongoose.startSession();
const options= {session, new:true}
let sourceAccount, destinationAccount;
const BASICSAVNGS_MAX_BALANCE = 1500;

const result = {
newSrcBalance: 0,
totalDestBalance:0,
transferedAt:moment.now()
}   


try {
session.startTransaction();
const source= await Account.findByIdAndUpdate(
{_id:sourceAccount._id},
{$inc:{balance:-amount}},
options
);

if(source.balance <0) {
// Source account should have the required amount for the transaction to succeed
const errorMessage='Insufficient Balance with Sender:';          
throw new ErrorHandler(404,errorMessage);            
}

const destination = await Account.findByIdAndUpdate(
{_id:destinationAccount._id},
{$inc:{balance:amount}},
options
); 
// The balance in ‘BasicSavings’ account type should never exceed Rs. 50,000
if((destination.accountType.name === 'BasicSavings') && (destination.balance > BASICSAVNGS_MAX_BALANCE)) {         
const errorMessage=`Recepient's maximum account limit reached`;
throw new ErrorHandler(404,errorMessage); 
}
await session.commitTransaction();
result.transferedAt= moment.now() //*UPDATE THE TRANSFER TIMESTAMP
result.newSrcBalance = source.balance; //*UPDATE THE SOURCE BALANCE
session.endSession();
// finding total balance in destination account
await User.findById(destination.user.id, async function(err,user) {
if(err) {
const errorMessage=`Recepient not found!`;
console.log(err);
throw new ErrorHandler(404,errorMessage);  
} else {                
if(user.accounts) {
await Account.find({
'_id' :{$in:user.accounts}
}, function(err,userAccounts) {                       
totalDestBalance = userAccounts.reduce( (accumulator,obj) => accumulator+obj.balance,0); 
result.totalDestBalance = totalDestBalance; //*UPDATE THE TOTAL BALANCE  
console.log(result); 
return result;                                                                                                              
});                    
}                
}
}); 

}
catch (error) {
// Abort transaction and undo any changes
await session.abortTransaction();
session.endSession();
throw new ErrorHandler(404,error);
} finally {
if(session) {
session.endSession();
}
}    
}
module.exports = transferAmount;

上述功能的结果是

{
newSrcBalance: 940,
totalDestBalance: 1060,
transferedAt: 1594982541900
}

但在下面的帖子请求中,它是{}

const result = await transferAmount(fromAccountId, toAccountId, amount);

您没有返回函数内部的内容。User.findById-这会接收一个返回内容的回调。您可以将其转换为async/await语法,或者必须使用promise来解析结果。

如下所示:

try {
const user = await User.findById(destination.user.id);
if (user.accounts) {
const userAccounts = await Account.find({ _id: { $in: user.accounts } });
totalDestBalance = userAccounts.reduce((accumulator, obj) => accumulator + obj.balance, 0);
result.totalDestBalance = totalDestBalance; //*UPDATE THE TOTAL BALANCE
console.log(result);
return result;
}
} catch (err) {
const errorMessage = `Recepient not found!`;
console.log(err);
throw new ErrorHandler(404, errorMessage);
}

或者:

return new Promise((resolve, reject) => {
User.findById(destination.user.id, async function(err, user) {
if (err) {
const errorMessage = `Recepient not found!`;
console.log(err);
reject(err);
} else {
if (user.accounts) {
await Account.find(
{
_id: { $in: user.accounts },
},
function(err, userAccounts) {
totalDestBalance = userAccounts.reduce((accumulator, obj) => accumulator + obj.balance, 0);
result.totalDestBalance = totalDestBalance; //*UPDATE THE TOTAL BALANCE
console.log(result);
resolve(result);
}
);
}
}
});
});

我可能错了,但在transferAmount函数中看不到return语句。

最新更新