簡體   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