Home > Net >  Cannot read properties of undefined (reading 'then')
Cannot read properties of undefined (reading 'then')

Time:11-23

I'm really bad at handling promises, and am trying to figure out why I'm getting this error. Here's what I'm doing:

testFunction(user_email, email_html).then(() => {
    //Some stuff
}).catch((error) => {
    //Some other stuff
})

function testFunction(user_email, email_html) {
    if (user_email) {
        sendEmail({ recipient: user_email, subject: "Some words", body: email_html, html: true })
    } else {
        return true
    }
}

sendEmail is a Firebase cloud function.

exports.sendEmail = functions.https.onCall((data, context) => {
    let is_html = data.html
    console.log("sendEmail is_html is ", is_html)
    let msg = {}
    if (!is_html) {
        msg = {
            to: data.recipient,
            from: '[email protected]',
            subject: data.subject,
            text: data.body
        }
    } else {
        msg = {
            to: data.recipient,
            from: '[email protected]',
            subject: data.subject,
            html: data.body
        }
    }
    console.log("sendEmail complete")
    return sgMail.send(msg)
});

What am I doing wrong?

CodePudding user response:

I was able to solve it by using async in front of the client-side function declaration rather than the Firebase function itself, and await in front of the call to the Firebase function.

CodePudding user response:

If the test function is executed successfully it returns a value which is placed in the () inside then else it returns an error and goes to catch. So if you wantd to print the result of the test function you would write:

testFunction(user_email, email_html).then((res) => {
    console.log(res)
}).catch((error) => {
    console.log(error)
})

But you need the res property ti act on it else if you dont care about the result as long as the excecution was successful you would write:

testFunction(user_email, email_html).then().catch((error) => {
    //Some other stuff
})

or if that doesn't work try skiping the then completly and write:

testFunction(user_email, email_html).catch((error) => {
    //Some other stuff
})
  • Related