Skip to content

Instantly share code, notes, and snippets.

@ovrmrw
Last active September 21, 2016 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ovrmrw/fff59c73f8c8fb089afcfbea880949bc to your computer and use it in GitHub Desktop.
Save ovrmrw/fff59c73f8c8fb089afcfbea880949bc to your computer and use it in GitHub Desktop.
An example to get an object which is resolved all (even nested) promises in Zone.
import 'babel-polyfill';
import 'zone.js/dist/zone-node';
declare const Zone: any;
Zone.current.fork({}).run(async () => {
// (async () => {
const obj = {
increment: Promise.resolve({
counter: 0
}),
nest: {
time: Promise.resolve({
serial: 0
}),
array: [
Promise.resolve({
a: 'a'
}),
Promise.resolve({
b: 'b'
})
],
},
promiseNest: Promise.resolve({
nestedPromise: Promise.resolve({
result: 'great.'
})
}),
num_prop: {
'0': 'foo'
},
'null': null,
'undefined': undefined,
'false': false,
willBeError: Promise.reject({
error: 'error'
})
};
async function resolveAllPromise<T>(obj: T | Promise<T>): Promise<T> {
let temp: any = obj;
if (temp instanceof Promise) {
try {
temp = await temp;
} catch (err) {
console.error(err);
temp = null;
}
temp = await resolveAllPromise(temp);
} else if (temp instanceof Object) {
for (let key in temp) {
if (temp[key] instanceof Promise) {
try {
temp[key] = await temp[key];
} catch (err) {
console.error(err);
temp[key] = null;
}
}
temp[key] = await resolveAllPromise(temp[key]);
}
}
return temp;
}
console.log(JSON.stringify(await resolveAllPromise(obj), null, 2));
// })();
});
/* OUTPUT
{
"increment": {
"counter": 0
},
"nest": {
"time": {
"serial": 0
},
"array": [
{
"a": "a"
},
{
"b": "b"
}
]
},
"promiseNest": {
"nestedPromise": {
"result": "great."
}
},
"num_prop": {
"0": "foo"
},
"null": null,
"false": false
"willBeError": null // <- Rejected.
}
*/
{
"compilerOptions": {
"target": "es2015",
"moduleResolution": "node",
"noImplicitAny": false,
"sourceMap": false,
"allowSyntheticDefaultImports": true,
"outDir": ".tscOutDir",
"skipLibCheck": true,
"strictNullChecks": true,
"lib": [
"es2017"
]
},
"exclude": [
"node_modules"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment