【问题标题】:Keep getting "Function returned undefined, expected Promise or value" when using a streaming API in Cloud Functions在 Cloud Functions 中使用流式 API 时,不断收到“函数返回未定义、预期的 Promise 或值”
【发布时间】:2018-07-20 18:26:08
【问题描述】:

我已经查看了 Stack Overfow 的所有内容,并且尝试了所有支持的解决方案,但仍然没有任何效果。

此代码的作用是获取一个链接并将其下载到 Firebase 存储中,当它成功时,它会使用视频名称更新用户值。我试过放一个“return true”,但所发生的只是代码被跳过,日志只是说它完成了。有解决这个问题的想法吗?

exports.downloadVideo = functions.database.ref('/Requests/{pushId}/linkURL').onUpdate(event => {

var videoFileName = Math.random() + '.mp4'
var link = event.data.val();

var video = youtubedl(String(link))

video.on('info', function(info){

    console.log('Download started');

});

const remoteWriteStream = bucket.file(videoFileName).createWriteStream({
metadata: { contentType: 'video/mp4'}
});

video.pipe(remoteWriteStream)
.on('error', (err) => {
console.log(err)
})
.on('finish',() => {

admin.database().ref('Requests').child(event.data.ref.parent.key).update({'linkLocation' : videoFileName})
console.log("success")
        });
    });

【问题讨论】:

    标签: node.js firebase firebase-storage google-cloud-functions


    【解决方案1】:

    由于您使用流式/事件式 API 来执行您的工作,因此您无法简单地从需要完成的最后一部分工作中返回一个承诺。在这种情况下,您需要创建自己的 Promise,安排在流式传输完成时解决它,必要时链接它,并返回最终的 Promise。以下是其工作原理的简要模板:

    return new Promise((resolve, reject) => {
        video.pipe(remoteWriteStream)
        .on('error', (err) => {
            console.log(err)
            reject() // reject the promise
        })
        .on('finish', () => {
            console.log("success")
            resolve() // resolve the promise
        });
    })
    .then(() => {
        // continue work after streaming is done
        return admin.database().ref('Requests').child(event.data.ref.parent.key)
            .update({'linkLocation' : videoFileName})
    });
    

    请注意,您必须在所有使用流式 API 并需要等待工作完成的时间应用此模式。考虑在函数中完成所有异步工作后才解决的 Promise 需要什么才能返回是非常重要的。

    如果你没有返回一个在所有工作完成后解决的承诺,它肯定不会按照你想要的方式运行。

    【讨论】:

    • 被包装的承诺并不总是解决或拒绝,有时会发生超时,然后包装承诺中的语句在函数完成后稍后执行。用于测试的视频文件大小最大为 100 MB
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 2021-10-22
    • 2019-08-06
    相关资源
    最近更新 更多