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

时间:2020-07-17 11:05:39

标签: javascript node.js async-await

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

    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);

2 个答案:

答案 0 :(得分:1)

您没有在函数内返回任何内容。 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);
                    }
                );
            }
        }
    });
});

答案 1 :(得分:0)

我可能是错的,但是在您的# print(df) date identifier value isnew 0 2019-12-31 a1 10 True 1 2019-12-31 a2 20 True 2 2019-12-31 a3 30 True 3 2020-01-31 a1 40 False 4 2020-01-31 a2 50 False 5 2020-01-31 a4 60 True 6 2020-01-31 a5 60 True 7 2020-02-28 a1 70 False 8 2020-02-28 a4 80 False 9 2020-02-28 a3 90 True 函数中看不到const users = [{ name: '10', pos: '0-0-0' }, { name: '20', pos: '0-0-1' }, { name: '21', pos: '0-0-1-1' }, { name: '40', pos: '0-0-11' }, { name: '30', pos: '0-0-6' }]; users.sort((a, b) => a.pos.localeCompare(b.pos, undefined, { numeric: true, sensitivity: 'base' })); console.log(users);语句。