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

Shu*_*tik 5 javascript node.js google-cloud-functions

我想使用async和添加awaitbucket.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 
                })
            }
        });
    })
})
Run Code Online (Sandbox Code Playgroud)

Joj*_*rte 7

在您package.json使用NodeJS引擎 8.

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

"engines": {
    "node": "8"
  },
Run Code Online (Sandbox Code Playgroud)

添加如下异步

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

  • 谢谢,我应该在上面的函数中写“async” (2认同)