提问者:小点点

为什么Await在异步函数中不工作?


我试图在一个异步函数中使用await。 不管怎样,我得到了错误

SyntaxError:await仅在async函数中有效

我不知道下面代码中的问题出在哪里。

insertPayrollAllowance: async function(companyId, jobId, basicSalary, employeeId, payrollId) {

        return new Promise((resolve, reject) => {
            sqlQuery = "SELECT * from tblJobAllowances Where tblJobAllowances.companyId = '" + companyId + "' and tblJobAllowances.jobId = '" + jobId + "' and deleterec = 0 order by id"
            db.executeQuery(sqlQuery, null, (err, result) => {
                if (err) {
                    reject(err);
                } else {

                    for (var i = 0; i < result.length; i++) {

                        var insStatus = false;
                        var allowanceId = result[i].allowanceId
                        var allowanceName = await this.getAllowanceName(companyId, allowanceId);
                        var amountType = result[i].typeOfAmount;
                        var amount = result[i].amount;
                        var amountCredited;
                        var taxable = result[i].taxable;

                        if ($.trim(amountType) == "FIXED AMT") {

                            amountCredited = parseFloat(amount.toString().replace(/,/g, ''));


                        } else if ($.trim(amountType) == "% Of Income") {

                            amountCredited = (parseFloat(basicSalary.toString().replace(/,/g, '')) / 100) * parseFloat(amount.toString().replace(/,/g, ''));

                        };

                        var info = {
                            companyId: companyId,
                            employeeId: employeeId,
                            payrollId: payrollId,
                            allowanceName: allowanceName,
                            amountType: amountType,
                            amount: amount,
                            amountCredited: amountCredited,
                            taxable: taxable
                        }

                        sqlQuery = "INSERT INTO tblPayrollAllowanceDetails SET ?"
                        db.executeQuery(sqlQuery, info, (err, result) => {
                            if (err) {
                                insStatus = false;
                            } else {
                                insStatus = true;
                            }
                        });

                    };

                    resolve(insStatus);

                }
            });
        });

    }

我会很高兴如果有人能指出为什么我得到这个错误。 如有任何协助,我们将不胜感激。


共1个答案

匿名用户

await位于另一个非异步函数内部

 db.executeQuery(sqlQuery, null, (err, result) => {

它位于箭头函数(err,result)=>内; {所以要修复它,只需添加async,如下所示:

db.executeQuery(sqlQuery, null, async (err, result) => {