Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

node.js - How to make Lambda function to wait till async operation finished?

I am new to NodeJS as well as AWS Lambda. I am creating a lambda function to get pre-signed URL for s3 put object. The problem I am facing here is that, call s3.getSignedUrl is async process which respond signed URL in callback but before this call responds, lambda function controls is reaching to the next line after this call and empty response is being received at client side. here is my code snippet of lambda function.


exports.handler = async (event) => {

  // Some stuff like reading inputs from request, initialising s3 object with AWS_ACCESS_KEY, and AWS_SECRET_KEY

  var response="default response";
   response =  s3.getSignedUrl('putObject', {
    "Bucket": myBucket,
    "Key": fileName,
    "ContentType": fileType
  }, function (err, url) {
    if (err) {
      console.log("error")
     return {
        statusCode: 200,
        body: JSON.stringify("Error in creating signed url"),
    };
    } else {
      console.log("generated "+url)
       return {
        statusCode: 200,
        body: JSON.stringify(url),
      };
    }
  });
  console.log("at end");
  return response;
};

If say in terms of log statements then before statement error or generated url at end log statement is printed and default response is returning. Can some body correct this code to responde the response being prepared inside callbacks of s3.getSignedUrl.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are just looking to create presigned url, you can use getSignedUrlPromise method that returns promise

exports.handler = async (event) => {
 return s3.getSignedUrlPromise("putObject", {
  Bucket: "my bucket",
  Key: "my file name",
  ContentType: "some file type",
 });
};

If you need customize the response

  exports.handler = async (event) => {
    return new Promise((resolve, reject) => {
    s3.getSignedUrl(
    "putObject",
    {
        Bucket: "my bucket",
        Key: "my file name",
        ContentType: "some file type",
    },
    (err, url) => {
        if (err) reject(err);
        if (url)
        resolve({
            statusCode: 200,
            body: url,
        });
    });
  });
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...