【问题标题】:how to fix async await logic on nodejs如何修复nodejs上的异步等待逻辑
【发布时间】:2021-07-19 11:56:39
【问题描述】:

如果它不存在,我正在尝试使用以下逻辑创建一个谷歌存储桶:

async function createBucket(id){
    const bucket = storage.bucket("bucket-" + id);
    const exists = await bucket.exists();
    if (!exists) {
      console.log("creating bucket>>" + "bucket-" + id);
      try {
        await bucket.create();
      } catch (e) {
        console.error("error in creating bucket>>>", e);
      }
    } else {
      console.log("it already exists >>" + exists);
    }
}

奇怪的是,我看到的是it already exists >> false,而我应该只能看到it already exists >> truecreating bucket>>bucket-123。任何解决此问题的帮助将不胜感激。谢谢!

【问题讨论】:

  • storage 是如何初始化的?为什么不使用承诺 bucket.exits.then(...
  • 这可能会受到竞争条件的影响。
  • storage.bucket("bucket-" + id); 也是异步调用吗?如果你写await storage.bucket("bucket-" + id);会发生什么?

标签: node.js google-api-nodejs-client


【解决方案1】:

问题是bucket.exists 返回一个包含结果的数组。在我的情况下,[false],这里似乎没有建议 https://googleapis.dev/nodejs/storage/latest/Bucket.html#exists 。以下解决了这个问题:

async function createBucket(id){
    const bucket = storage.bucket("bucket-" + id);
    const [exists] = await bucket.exists();
    if (!exists) {
      console.log("creating bucket>>" + "bucket-" + id);
      try {
        await bucket.create();
      } catch (e) {
        console.error("error in creating bucket>>>", e);
      }
    } else {
      console.log("it already exists >>" + exists);
    }
}

【讨论】:

  • 谢谢你,刚刚在谷歌云函数 nodejs14 中尝试了 'latest' 作为包含参考,在存在()上得到了无效的存储桶名称......仍然为你工作?
猜你喜欢
  • 2021-11-18
  • 1970-01-01
  • 2022-11-20
  • 1970-01-01
  • 2018-03-22
  • 2020-02-26
  • 2019-07-20
  • 2020-03-31
  • 1970-01-01
相关资源
最近更新 更多