繁体   English   中英

类型错误:无法读取未定义的属性“then”。 当我尝试运行 updatefirst 函数时出现此错误

[英]TypeError: Cannot read property 'then' of undefined. Getting this error when I am trying to run updatefirst function

我正在尝试运行 updatefirst 函数,但即使我将预定义的值传递给 get_plo_amount 中的解析函数时,也会一次又一次地得到相同的错误。 console.log(result) 行运行表明,在获取数据时没有问题. 我不知道我在这里做错了什么:(。任何帮助将不胜感激。谢谢。

const get_plo_amount = function(p){
    plo.findOne({phone : p}).then((result) => {
        console.log(result) //this line is running
        return new Promise((resolve,reject) => {
            resolve(result.daily_amount)
        })

    }).catch((e) => {
        console.log("catch")
        return new Promise((resolve,reject) => {
            reject(e)
        })
    })

}

//updatefirst
const updatefirst = function(plo,date){
    driver.find({associated_plo : plo}).then((result) => {
        //console.log(result)//delete this
        get_plo_amount(plo).then((amount) => {
            console.log(amount)
            var arr
            for(i=0;i<result.length;i++){
                var pdue = parseInt(result[i].balance) + amount
                var d_obj = {
                    driver : result[i].name,
                    phone : result[i].phone,
                    auto_number : result[i].auto_number,
                    amount : pdue,
                }
             //   console.log(d_obj)//delete this
                arr[i] = d_obj
            }

            const obj = {
                associated_plo : plo,
                date : date,
                earning : "0",
                payments : arr
            }
            const t = new transactions(obj)

            t.save().then(() => {
                return "success"
            }).catch((e) => {
                return e
            })

        }).catch((e) => {
            console.log(e)
            return e
        })


    }).catch((e) => {
        console.log(e)
        return e
    })
}

您应该返回一个承诺,以使then()方法工作。 尝试像这样更新你的函数:

const get_plo_amount = function(p){
    return plo.findOne({phone : p}).then((result) => {
        console.log(result) //this line is running
        return new Promise((resolve,reject) => {
            resolve(result.daily_amount)
        })

    }).catch((e) => {
        console.log("catch")
        return new Promise((resolve,reject) => {
            reject(e)
        })
    })

}

还有 2 个变化

  1. 您可以返回result.daily_amount而无需创建另一个承诺
  2. catch 中的 promise 被拒绝,所以你不妨删除 catch
const get_plo_amount = function(p){
    return plo.findOne({phone : p}).then((result) => {
        console.log(result) //this line is running
        result.daily_amount;
    });
}

暂无
暂无

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

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