Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Last active February 12, 2018 23:50
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 xeoncross/9449442e66e2620842483d0199a2b4d8 to your computer and use it in GitHub Desktop.
Save xeoncross/9449442e66e2620842483d0199a2b4d8 to your computer and use it in GitHub Desktop.
Examples of using Promises in Javascript
// You can catch an exception, modify it, then throw again. Handy for passing information (like SQL queries or state) up the chain of error handlers.
function doSomething(user) {
return Promise.resolve()
.then(() => {
throw new Error("Some Problem");
})
.catch(err => {
throw new Error("Child: " + err.message + ' User:' + user);
});
}
Promise.resolve()
.then(() => doSomething('John'))
.catch(err => {
console.log("Parent: " + err.message);
});
Parent: Child: Some Problem User:John
const promises = [];
const n = v =>
new Promise(r =>
setTimeout(() => {
console.log('worker', v);
r(v);
}, v));
promises.push(n(1));
promises.push(n(2));
promises.push(Promise.reject(new Error(3)).then(console.log));
promises.push(n(4));
promises.push(n(5));
promises.push(Promise.reject(new Error(6)).catch(console.log));
promises.push(n(7));
promises.push(n(8));
// All promises start, they they don't effect each other
Promise.all(promises)
.then(r => console.log('Results', r))
.catch(e => console.log('ERROR', e.message));
Error: 6
at Object.<anonymous> (/Users/owner/Desktop/CI/spectrum/app/server/demos/chain.js:15:30)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:578:3
ERROR 3
worker 1
worker 2
worker 4
worker 5
worker 7
worker 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment