D. Walsh D. Walsh - 3 months ago 20
Javascript Question

How to chain promises with arrays

Problem: Create an AWS Lambda function to resize uploaded S3 pictures using Node 4.3 and graphics magic.

My Problem: I cannot figure out how to integrate an array of picture objects into the promise flow. All of the stack examples that I can find show an array of object promisified when all data is known. But I need to read the image data first and then pass it to the resize function.

The function below completes before resizePicture resolves. I know the issue is not returning Promises and resolving in the correct order. I'm stumped.

var pictureSizes = [
{width: 100, size: 'thumbnail', suffix: '_t'},
{width: 300, size: 'small', suffix: '_s'},
{width: 600, size: 'medium', suffix: '_m'},
{width: 1000, size: 'large', suffix: '_l'}
];

exports.handler = function(event, context) {

var srcBucket = event.Records[0].s3.bucket.name;.
var srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));
var dstBucket = srcBucket + "pictures";
var typeMatch = srcKey.match(/\.([^.]*)$/);
var fileName = path.basename(srcKey);

downloadImage({ Bucket: srcBucket, Key: srcKey})
.then(result => pictureSizes.map(picture => resizePicture(result, picture)))
.then(result => saveImage(result, dstBucket, fileName))
.catch(err => console.log('error', err))
}

function downloadImage(params) {
console.log('download Image', params);
return new Promise(function(resolve, reject) {
s3.getObject(params, function(err, data) {
if (err) {
reject(err);
}
resolve(data);
})
});
}

function resizePicture(result, picture) {
return new Promise(function(resolve, reject) {
const extension = result.ContentType.split('/')[1];
gm(result.Body)
.resize(picture.width)
.toBuffer(extension, function(err, buffer) {
if (err) {
reject(err);
} else {
resolve({
key: `${picture.suffix}.${extension}`,
binary: buffer,
ContentType: result.contentType
})
}
});
})
}

function saveImage(result, dstBucket, fileName) {
return new Promise(function(resolve, reject) {
s3.putObject({
Bucket: dstBucket,
Key: `${fileName}${result.key}`,
Body: result.binary,
ContentType: result.ContentType
}, function(err, data) {
if (err) {
reject(err);
}
resolve(data);
})
})
}

Answer

Ah, you've almost got it! You need to create a watcher for an array of promises you generate here: pictureSizes.map(picture => resizePicture(result, picture)).

Try Bluebird's Promise.map, and your line can read:

.then(result => Promise.map(pictureSizes, picture => resizePicture(result, picture)))

And if you want to not have any nested functions, #bind is what you want:

.then(result => Promise.map(pictureSizes, picture => resizePicture.bind(null, result)))