简体   繁体   English

解决bluebird对对象数组的承诺

[英]resolving bluebird promise for array of object

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. 似乎在bufferData对象内部没有解决诺言。 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. 这是我想要的,但是我无法附加索引。

You're Promise.all is being given an array of objects that contain promises, not the promises themselves. 您的Promise.all是,所有对象都被赋予了一个包含承诺而不是承诺本身的对象数组。 You just need to make sure the array is an array of actual promises: 您只需要确保该数组是实际的Promise数组即可:

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 . 为了解决这个问题,您必须将当前索引包含在Promise中(例如,不要通过闭包访问它),否则它们都将等于imagePaths.length

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM