问题
I need to use the map bluebird (Promise lib) but to return an object, instead of an array.
Currently, I'm using it like this (but it is wrong):
return new Promise(function(resolve, reject) {
return Promise.map(files, function(file) {
// LOGIC
resolve({
// object here
})
}, { concurrency: 3000 })
});
The reason is simple: I need the concurrency: 3000, and I need to return the object. So the new Promise is to return the object, and not an array, and the map is because of the concurrency.
Are there any other methods of bluebird which could help me achieve what I need? I searched a lot and I didn't find anything.
回答1:
If you're trying to produce an object that is of the form:
var result = {
file1: result1,
file2: result2
};
Where file1
and file2
are the names of the files and result1
and result2
are the result of some async operation on file1
and file2
, then you can do that like this:
var result = {};
return Promise.map(files, function(file) {
return doSomeAsync(file).then(function(data) {
// add to our result object
result[file] = data;
});
}, {concurrency: 3000}).then(function() {
// make the result obj be the final resolved value of Promise.map()
return result;
});
This will make the result
object above be the final resolved value of the Promise.map()
promise that is returned from the function this is in.
If the first code block above is not the type of "object" you want to produce, then please explain further exactly what type of output you want.
Also, you probably want to avoid the promise anti-pattern where you create unnecessary promises rather than just chain or return the ones you already have.
回答2:
I don't think there is a method for this directly in Bluebird. But you can always return an array and you can convert it to object later. Thus you don't need Bluebird to do it. E. g. using Lodash you can use zipObject:
_.zipObject([['fred', 30], ['barney', 40]]);
// → { 'fred': 30, 'barney': 40 }
来源:https://stackoverflow.com/questions/33507878/how-to-use-bluebird-map-and-return-object