New promise helper, resolvePromiseProperties

`resolvePromiseProperties` takes on object and returns a promise which
resolves to a copy of the object. This copy has all its immediate
properties which were Promises replaced with the resolved value of
those promises. Promises are run with `Promise.all`. Errors are passed
up to the outer promise chain.

Example usage:

```js
resolvePromiseProperties({
  promise: Promise.resolve("this property will resolve to this string"),
  nonPromise: "this will remain the same",

  // you can nest the function
  nestedPromiseInside: resolvePromiseProperties({
    nestedPromise: Promise.resolve("this will resolve"),
    nestedNonPromise: "this stays the same",
  }),
})
.then(obj => console.log(obj))

```

That will produce the following output:

```js
{
  promise: "this property will resolve to this string",
  nonPromise: "this will remain the same",
  nestedPromiseInside: {
    nestedPromise: "this will resolve",
    nestedNonPromise: "this stays the same",
  },
}
```
This commit is contained in:
Benaiah Mischenko 2017-03-17 13:56:34 -07:00
parent c079cb96c4
commit 1dc2841609

View File

@ -1,3 +1,23 @@
import { zipObject } from 'lodash';
export const filterPromises = (arr, filter) =>
Promise.all(arr.map(entry => filter(entry)))
.then(bits => arr.filter(entry => bits.shift()));
export const resolvePromiseProperties = obj =>
(new Promise((resolve, reject) => {
// Get the keys which represent promises
const promiseKeys = Object.keys(obj).filter(
key => obj[key] instanceof Promise);
const promises = promiseKeys.map(key => obj[key]);
// Resolve all promises
Promise.all(promises)
.then(resolvedPromises => resolve(
// Return a copy of obj with promises overwritten by their
// resolved values
Object.assign(obj, zipObject(promiseKeys, resolvedPromises))))
// Pass errors to outer promise chain
.catch(err => reject(err));
}));