错误:使用Firebase云功能

时间:2017-03-22 11:29:56

标签: node.js firebase firebase-storage

我想使用Firebase函数调整存储在Firebase存储中的图像。

基于Firebase小组提供的示例:https://github.com/firebase/functions-samples/blob/master/quickstarts/thumbnails/functions/index.js我尝试编写由数据库事件触发的函数。

以下是代码中最有趣的部分:

exports.myFunction = functions.database.ref('...').onWrite(event => {

        ...

        // Create thumbnails
        createThumbnail(1, ...);
        createThumbnail(2, ...);
        createThumbnail(3, ...);

         ...

        return; // <- Is this necessary ?
});

function createThumbnail(...) {

    ...

    return bucket
        .file(originalFilepath)
        .download({
            destination: tempFilePath
        })
        .then(() => {

            console.log('OK');

            ...

            // Generate a thumbnail using ImageMagick.
            return spawn('convert', [tempFilePath, '-thumbnail', dimension + 'x' + dimension + '>', tempFilePath])
                .then(() => {

                    ....

                    // Uploading the thumbnail.
                    return bucket.upload(tempFilePath, {
                            destination: thumbnailUrl
                        })
                        .then(() => {

                              ...

                            // Save thumbnailUrl in database
                            return admin.database().ref(...).set(thumbnailUrl);
                        });
                });
        });
}

一切看起来都不错。但是代码永远不会转到console.log('OK');,我收到此错误:

Error: read ECONNRESET
    at exports._errnoException (util.js:1026:11)
    at TCP.onread (net.js:569:26)

有人知道可能是什么错误吗?

谢谢

1 个答案:

答案 0 :(得分:4)

问题是您正在返回一个Promise,它在所有异步作业完成之前完成。

执行此操作时:

createThumbnail(1, ...);
createThumbnail(2, ...);
createThumbnail(3, ...);
...
return;

您正在启动3个异步createThumbnail任务,但您将立即返回。因此,Cloud Functions实例会关闭,而您的3 createThumbnail没有时间来完成,而当您收到ECONNRESET错误时就是这样。

每个createThumbnail都会返回一个Promise。您需要做的是使用Promise.all返回完成3 Promise次承诺时完成的createThumbnail

const listOfAsyncJobs = [];
listOfAsyncJobs.push(createThumbnail(1, ...));
listOfAsyncJobs.push(createThumbnail(2, ...));
listOfAsyncJobs.push(createThumbnail(3, ...));
...
return Promise.all(listOfAsyncJobs); // This will ensure we wait for the end of the three aync tasks above.
相关问题