尝试将文件上传到Google存储时承诺优先权

时间:2018-06-07 20:18:17

标签: node.js promise google-cloud-storage

我正在将文件上传到Google Cloud。完成后,我想返回文件URL和一些元数据。我想这样做:

blobStream.on('finish', () => {

                var fileSize;
                var fileCreated;

                fileUpload.getMetadata()
                    .then(metadata => { 
                        const mObj = metadata[0];
                        fileSize = mObj.size;
                        fileCreated = mObj.timeCreated;
                });

                fileUpload.getSignedUrl({
                    action: 'read',
                    expires: '03-09-2491'
                }).then(signedUrl => {
                    let response = {};
                        response.name = newFileName;
                        response.size = fileSize;
                        response.created = fileCreated;
                        response.url = signedUrl[0];
                    resolve(response);
                }).catch(error => {
                    reject(error);  
                });

            });

问题是,getSignedUrl方法总是先触发,并且永远不会填充“fileSize”+“fileCreated”。

我认为我需要链接事件,因此getMetadata首先发生,但对Node(和Promises)来说相对较新,可以使用一些建议。

编辑每个BERGI的回复:(以下方法有效)

uploadFileToStorage(file) {

    let utils = new Utils();
    let newFileName = `${utils._guid()}-${Date.now()}`;
    let bucket = admin.storage().bucket();
    let filePath = url.format('audioFiles/' + newFileName);
    let fileUpload = bucket.file(filePath);

    let prom = new Promise(function(resolve, reject) {

        if (!file) {
            reject('No file provided');
            return;
        }

        const blobStream = fileUpload.createWriteStream({
            metadata: {
                contentType: file.mimetype
            }
        });

        blobStream.on('error', (error) => {
            reject('Something is wrong! Unable to upload at the moment.');
            return;
         });

        blobStream.on('finish', resolve);

        blobStream.end(file.buffer);

      }).then(() => { 

        return Promise.all([
            fileUpload.getMetadata(),
            fileUpload.getSignedUrl({
                action: 'read',
                expires: '03-09-2491'
            }),
        ]);

    }).then(([metadata, signedUrl]) => {

        const fileSize = metadata[0].size;
        const fileCreated = metadata[0].timeCreated;
        const response = {
            name: newFileName,
            size: fileSize,
            created: fileCreated,
            url: signedUrl[0],
        };

        return response;

    });

    return prom;

}

1 个答案:

答案 0 :(得分:2)

不要创建两个独立的承诺,也不要使用外部范围变量,这些变量在分配时永远不会知道。相反,使用Promise.all等待多个承诺:

new Promise(resolve => {
    blobStream.on('finish', resolve);
}).then(() => {
    return Promise.all([
        fileUpload.getMetadata(),
        fileUpload.getSignedUrl({
            action: 'read',
            expires: '03-09-2491'
        }),
    ]);
}).then(([metadata, signedUrl]) => {
    const fileSize = metadata[0].size;
    const fileCreated = metadata[0].timeCreated;
    const response = {
        name: newFileName,
        size: fileSize,
        created: fileCreated,
        url: signedUrl[0],
    });
    return response;
});

还要避免using further promises inside the Promise constructor