Using async in the Amazon Lambda example?

I am reviewing Amazon Lambda sample code for resizing images in S3 buckets. Example code (for clarity convenience):

// Download the image from S3, transform, and upload to a different S3 bucket.
async.waterfall([
  function download(next) {
    // Download the image from S3 into a buffer.
    s3.getObject({Bucket: srcBucket, Key: srcKey}, next);
  },
  function tranform(response, next) {
    gm(response.Body).size(function(err, size) {
      // do resize with image magic
    }
  }
]);
//... more handling code

      

... shows that they are using an asynchronous waterfall. However, each of these orderly steps seems to rely on the results of the previous function. Essentially, this is a sequential operation.

What is the advantage of using asynchronous waterfall here? Is this something to do with the Lambda engine at Amazon, or just a sane design decision at node?

+3


source to share


1 answer


This is essentially a sensible design decision as you described it. Instead of getting caught up in callback hell , the example author basically flattened out the code using waterfall

.

An alternative code would look like this:



s3.getObject({Bucket: srcBucket, Key: srcKey}, function(response){
  gm(response.Body).size(function(err, size) {
  // do resize with image magic
  }
});

      

Which is less readable and can become much more complex and much less readable as steps are added to processing.

+4


source







All Articles