如何添加异步到谷歌云功能?

时间:2019-02-20 05:40:45

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

我想使用async并在await函数中添加bucket.upload。我也在函数中使用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 
                })
            }
        });
    })
})
 

1 个答案:

答案 0 :(得分:0)

package.json中使用NodeJS引擎8。

默认情况下,GCF使用版本6。要使用async/await,必须在package.json内进行更改或添加以下内容

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

添加如下所示的异步

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