【问题标题】:firebase function returned undefined expected Promise or Valuefirebase 函数返回未定义的预期承诺或值
【发布时间】:2019-06-09 03:16:57
【问题描述】:

我的代码如下所示。在这两种情况下,它都会在我返回 null 的地方引发错误。我也应该在函数末尾返回 null 吗?我担心这是否会使功能不等待完成

exports.on_user_created_update_generate_barcode = functions.database.ref("/users/{id}")
.onCreate((snapshot, context) => {
    console.log("start of on_user_created_update_generate_barcode ")   
    const user = snapshot.val();
    const referralCode = user._referralCode
    const uid = context.params.id
    console.log("Referral code is:" + referralCode + " for user:" + uid)



    bwipjs.toBuffer({
        bcid:        'code128',       // Barcode type
        text:        referralCode,    // Text to encode
        scale:       3,               // 3x scaling factor
        height:      10,              // Bar height, in millimeters
        includetext: true,            // Show human-readable text
        textxalign:  'center',        // Always good to set this
    }, function (err, png) {
        if (err) {
            console.err("failed to generate bar code:::" + err)
            return null
        } else {
            console.log("png generated")
            //console.log(png)
            const pngImg = 'data:image/png;base64,' + png.toString('base64')
            var db = admin.database();
            var userRef = db.ref('users')
            return userRef.child(uid).update({"_barcode": pngImg})
        }
    });

})

【问题讨论】:

    标签: javascript firebase google-cloud-functions


    【解决方案1】:

    错误消息是正确的 - 您没有从函数返回任何内容,这与返回 undefined 相同。相反,您正在做的是从您传递给bwipjs.toBuffer() 的函数回调中返回 null。该内部函数的返回值不会传播到外部函数。

    如果您只是从函数的顶层返回 null,您可能会停止该错误消息,但代码将无法正常工作。 Cloud Functions 将在函数返回一个非 Promise 的值后关闭在函数内部启动的所有异步工作。它可能看起来什么都不做。

    您需要做的是返回一个 Promise,当您的函数中的所有异步工作完成时,该 Promise 将解决。现在,这看起来像是对 toBuffer() 的调用,以及对实时数据库的 update() 的调用。

    您可能会发现函数中的documentation on async programming 很有帮助。你可能还想看这个video series on dealing with promises in Cloud Functions

    【讨论】:

    • 你的解释很有道理。如何将其转换为这种方式的承诺?
    • 这不是简单的“转换”。您需要按照我描述的方式使用 Promise 来编写代码。
    猜你喜欢
    • 2020-12-23
    • 2019-05-11
    • 2018-06-17
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2018-12-17
    相关资源
    最近更新 更多