【问题标题】:Cloud Functions and Storage: Is deleting file asynchronous?Cloud Functions and Storage:删除文件是异步的吗?
【发布时间】:2019-12-08 10:17:39
【问题描述】:

在我的 Google Cloud Functions 脚本中,我想使用以下代码删除 Google Cloud Storage 文件:

const gcs = require('@google-cloud/storage')()

exports.deletePost = functions.https.onRequest((request, response) => {

    if(!context.auth) {
        throw new functions.https.HttpsError('failed-precondition', 'The function must be called while authenticated.');
    }

    const the_post = request.query.the_post;

    const filePath = context.auth.uid + '/posts/' + the_post;
    const bucket = gcs.bucket('android-com')
    const file = bucket.file(filePath)
    const pr = file.delete()


});

问题是我还需要在删除存储文件后删除 Google Firebase Firestore 数据库条目。所以我想知道我是否可以在例如delete返回的承诺中做到这一点?

PS : 我没有找到文档

【问题讨论】:

    标签: google-cloud-functions google-cloud-storage


    【解决方案1】:

    代码file.delete() 是异步的,并返回一个Promise,如Google Cloud Storage: Deleting objects 文档中所定义。

    要从您的 Cloud Storage 存储分区之一中删除对象:

    // Imports the Google Cloud client library
    const {Storage} = require('@google-cloud/storage');
    
    // Creates a client
    const storage = new Storage();
    
    /**
     * TODO(developer): Uncomment the following lines before running the sample.
     */
    // const bucketName = 'Name of a bucket, e.g. my-bucket';
    // const filename = 'File to delete, e.g. file.txt';
    
    // Deletes the file from the bucket
    await storage
      .bucket(bucketName)
      .file(filename)
      .delete();
    
    console.log(`gs://${bucketName}/${filename} deleted.`);
    

    不是很清楚,但是因为使用了await 语法,这意味着它右边的表达式的结果是一个Promise。

    注意:大部分有用的谷歌云存储文档都可以在here找到。

    【讨论】:

    • 如果发生阻碍删除的错误,会抛出异常,对吧?我怎么能抓住它? (在文档中,他们使用了ok() 函数?)
    • 我下面的代码正确吗? :const promise = await gcs.bucket('android-framework-f3b92.appspot.com').file(filePath).delete(); if(!promise.ok()) { throw new functions.https.HttpsError('unknown', 'Unable to delete the image.'); } // No error
    • 通常,要捕获 Promise 上的错误,您需要将 .catch((err) => {...}) 附加到 Promise 链上。但是当你使用await语法时,被拒绝的promise的值应该像异常一样被抛出并且可以被try/catch语法收集。
    最近更新 更多