Error: read ECONNRESET when resizing image with Firebase Cloud Functions

Error: read ECONNRESET when resizing image with Firebase Cloud Functions

我想使用 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)

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

谢谢

问题是您正在 return 一个在所有异步作业完成之前完成的 Promise。

当你这样做时:

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

您正在启动 3 个异步 createThumbnail 任务,但您正在 return 立即执行。因此,Cloud Functions 实例被关闭,您的 3 createThumbnail 没有时间完成,这就是您收到 ECONNRESET 错误的时候。

每个 createThumbnail return 都是一个 Promise。您需要做的是使用 Promise.all 到 return 一个 Promise,当 3 createThumbnail Promise 完成时完成:

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.