首页 > 解决方案 > Cloud Functions and Storage:删除文件是异步的吗?

问题描述

在我的 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-functionsgoogle-cloud-storage

解决方案


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

要从您的某个 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。

注意:大部分有用的 Google Cloud Storage 文档都可以在此处找到。


推荐阅读