Reputation: 105
I want to read the image paths, convert them into binary data, append an index and then do something else after all the files have been converted. I have the following code:
var bufferData = [];
for (var i = 0; i < imagePaths.length; i++) {
bufferData.push({
data: fs.readFileAsync(imagePaths[i]),
index: i
}
);
}
Promise.all(bufferData).then(function (data) {
console.log(data);
//do something
});
which returns
[ { data:
Promise {
_bitField: 134217728,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined },
index: 0 } ]
It seems like the promise is not being resolved inside the bufferData object. What do I need to do to resolve the promise?
If i do
var bufferData = [];
for (var i = 0; i < imagePaths.length; i++) {
bufferData.push(fs.readFileAsync(imagePaths[i]));
}
Promise.all(bufferData).then(function (data) {
console.log(data);
//do something
});
it returns:
[ <Buffer ff d8 ff e1 18 b9 45 78 69 66 00 00 49 49 2a 00 08 00 00 00 09 00 0f 01 02 00 06 00 00 00 7a 00 00 00 10 01 02 00 0e 00 00 00 80 00 00 00 12 01 03 00 ... > ]
which is what I want, but I was not able to append the index.
Upvotes: 0
Views: 330
Reputation: 32146
You're Promise.all
is being given an array of objects that contain promises, not the promises themselves. You just need to make sure the array is an array of actual promises:
for (var i = 0; i < imagePaths.length; i++) {
var fileIndexPromise = Promise.all([
fs.readFileAsync(imagePaths[i]),
i
])
bufferData.push(fileIndexPromise.then(([result, index]) => ({
data: result,
index: index
})));
}
Promise.all(bufferData).then(function (data) {
console.log(data);
//do something
});
EDIT: It occurs to me that my original post would have given the incorrect value for the index. To fix that, you'll have to include the current index as part of the promise (eg, don't access it via the closure), as otherwise they would all be equal to imagePaths.length
.
Upvotes: 1