How to allow a set of promises and values ​​using Bluebird

I have list values

xs = [1, 2, 3, 4]

I also have an asynchronous function squarethat returns the promise of the square of the argument passed to it. I want to pass the elements of my list to my function in parallel, and then collect the promises into an array and wait for them to complete. I can formulate this as a map / reduce operation.

Promise
.map(xs, function(x) {
        return square(x)
    }
)
.reduce(function(ys, y) {
        return ys.concat(y)
    }, [])

This ultimately returns the allowed values.

[1, 4, 9, 16]

Simple enough. Now say that I want to include the original argument in the answer array like this.

[{x:1, y:1}, {x:2, y:4}, {x:3, y:9}, {x:4, y:16}]

Now the difficult part I have is a list of objects, each of which at the beginning of the reduction step has a promise inherent in the property y. How to write Bluebird code to do this, reduce the step?

+4
2

, ES6 Babel .

import {props, map} from "bluebird";

map(xs, x => props({x, y:square(x)}); // do something with it :)

Promise.props .

+3

reduce. map:

Promise.map(xs, function(x) {
    return f(x).then(function(y) {
        return {x:x, y:y};
    });
})

, , map .

, ,

Promise.map(xs, f).map(function(y, i) {
    return {x:xs[i], y:y};
})

, xs[i] .

+5

All Articles