Promise to object
Resolves an object containing promises, works with nested promises and arrays.
Works with Bluebird.
Resolution is concurrent.
How to use ?
Basic usage :
global.Promise.toObject = require('promise-to-object');
Promise.toObject({
foo: 'bar',
greet: Promise.resolve('Hello world !')
})
.then(result => {
console.log(result.foo);
console.log(result.greet);
})
.catch(error => {
console.error(error);
});
Copying the original object :
Useful if you intend to reuse the object with promises later.
Promise.toObject(someObjectWithPromises, { copy: true })
Works with unlimited nested objects :
let someObjectWithPromises = {
foo: 'bar',
nested: {
nestedGreeting: Promise.resolve('Hello world !')
}
};
Promise.toObject(someObjectWithPromises, { copy: true })
.then(result => {
console.log(result.foo);
console.log(result.nested.nestedGreeting);
})
Works with Arrays
Mixed arrays will return the array with the result of promise at the same index
the promise was.
Example with Array as first arg :
Promise.toObject([
'foo',
Promise.resolve('bar'),
{
hello: Promise.resolve('world')
}
])
.then(result => {
console.log(result);
});
Or array in object :
Promise.toObject({
foo: 'bar',
someArrayWithPromises: [
'hello',
Promise.resolve('world !')
]
})
.then(result => {
console.log(result);
})
Promise rejection
Rejection will occur when first promise rejection happens.
Promise.toObject({
foo: new Promise((resolve, reject) => {
setTimeout(() => reject('1st promise rejection.'), 300)
}),
bar: new Promise((resolve, reject) => {
setTimeout(() => reject('2nd promise rejection.'), 100)
})
})
.catch(error => {
console.log(error);
});