【问题标题】:How to add async to google cloud function?如何将异步添加到谷歌云功能?
【发布时间】:2019-07-13 17:45:14
【问题描述】:

我想使用async 并在bucket.upload 函数中添加await。我也在我的函数中使用cors。但我无法添加async,因为它会报错。

这是我的代码:

exports.registerAdminUser =  functions.https.onRequest(( request, response ) => {
    return  cors (request,response, ()=> {
        const body = request.body;
        const profile_pic = body.profile_pic;

        const strings = profile_pic.base64.split(',');
        const b64Data = strings[1];
       
        const contenttype = profile_pic.type;
        const uid = uniqid();
        const uploadName = uid + profile_pic.name
        const fileName = '/tmp/' + profile_pic.name;
        
        fs.writeFileSync(fileName, b64Data, "base64", err => {
            console.log(err);
            return response.status(400).json({ error: err });
          });



        const bucketName = 'my-bucketname.io';
        const options = {
            destination: "/images/admin/" + uploadName,
            metadata: {
              metadata: {
                uploadType: "media",
                contentType: contenttype ,
                firebaseStorageDownloadTokens: uid
              }
            }
          };
        const bucket = storage.bucket(bucketName);
        bucket.upload(fileName,options, (err, file) => {
            if(!err){
          const imageUrl = "https://firebasestorage.googleapis.com/v0/b/" + bucket.name + "/o/" + encodeURIComponent(file.name) + "?alt=media&token=" + uid;
                return response.status(200).json(imageUrl);
            } else {
                return response.send(400).json({
                    message : "Unable to upload the picture",
                    error : err.response.data 
                })
            }
        });
    })
})

【问题讨论】:

标签: javascript node.js google-cloud-functions


【解决方案1】:

在您的 package.json 中使用 NodeJS 引擎 8。

默认情况下,GCF 使用版本 6。为了能够使用 async/await,您必须在 package.json 内更改或添加以下内容

"engines": {
    "node": "8"
  },

像下面这样添加异步

exports.registerAdminUser =  functions.https.onRequest(
  async ( request, response ) => {
      /**/
      await someFunction(/**/)...
  }
);

【讨论】:

  • 谢谢,在上面的函数中我应该在哪里写async
  • 你可以在( request, response )之前写它,它看起来像exports.registerAdminUser = functions.https.onRequest(async( request, response )
【解决方案2】:

由于 async/await 是 ES2017 功能,您需要将其添加到您的 .eslintrc.js 中:

module.exports = {
    // ...
    "parserOptions": {
        "ecmaVersion": 2017
    },
    // ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2021-01-25
    • 2017-11-14
    • 1970-01-01
    • 2019-12-08
    • 2018-12-01
    • 2019-05-14
    相关资源
    最近更新 更多