繁体   English   中英

SyntaxError: await 仅在 nodeJs 中的异步 function 中有效

[英]SyntaxError: await is only valid in async function in nodeJs

I have created the following function that makes a call to a third party API to create an order and on the response iam calling model function that checks if a user with the user ID exits or not and some operation is done accordingly.

createOrder: async function (req, res, next) {
    
    let formData = req.body;

    razorPayInstance.instance.orders.create({
        amount: formData.amount * 100,
        currency: "INR", 
        payment_capture: 1       
    })
    .then(response => {
        let planSubscription = await PlanSubscription.findOne({ user_id:formData.user_id });
        if(planSubscription) {
            // do something
        } else {
         // do something
        }

        return res.status(200).json(res.fnSuccess(response));
    })
    .catch(error => {
        console.log(error);
    });
    
}

我在节点控制台中收到以下错误: let planSubscription = await PlanSubscription.findOne({ user_id:formData.user_id }); ^^^^^ SyntaxError: await is only valid in async function

谁能指出这里有什么问题

您不能await不是async的 function 中的某些表达式。 只需在内部使用async then即可。在此处查看有关等待的更多信息

createOrder: async function (req, res, next) {
        
        let formData = req.body;
    
        razorPayInstance.instance.orders.create({
            amount: formData.amount * 100,
            currency: "INR", 
            payment_capture: 1       
        })
        .then(async(response) => { //change here
            let planSubscription = await PlanSubscription.findOne({ user_id:formData.user_id });
            if(planSubscription) {
                // do something
            } else {
             // do something
            }
    
            return res.status(200).json(res.fnSuccess(response));
        })
        .catch(error => {
            console.log(error);
        });
        
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM