Skip to content

Instantly share code, notes, and snippets.

@sebastien-p
Last active February 23, 2018 08:43
Show Gist options
  • Save sebastien-p/e08d265a2a9cd76799ca0e80d6c79f51 to your computer and use it in GitHub Desktop.
Save sebastien-p/e08d265a2a9cd76799ca0e80d6c79f51 to your computer and use it in GitHub Desktop.
Promises chaining
promiseA.then(function (resultA) {
promiseB.then(function (resultB) {
object.method(arg1, arg2, function (resultC) {
console.log(resultC);
});
});
});
promiseA.then(function (resultA) {
return promiseB;
}).then(function (resultB) {
object.method(arg1, arg2, function (resultC) {
console.log(resultC);
});
});
promiseA.then(function (resultA) {
return promiseB;
}).then(function (resultB) {
// Now returns a promise
return object.method(arg1, arg2);
}).then(function (resultC) {
console.log(resultC);
});
// What about more than 1 or 2 nesting levels?
promiseA.then(function (resultA) {
promiseB.then(function (resultB) {
object.method(arg1, arg2, function (resultC) {
promiseC.then(function (resultC) {
promiseD.then(function (resultD) {
// And so on...
});
});
});
});
});
// Promise style
promiseA.then(function (resultA) {
return promiseB;
}).then(function (resultB) {
// Now returns a promise
return object.method(arg1, arg2);
}).then(function (resultC) {
return promiseD;
}).then(function (resultD) {
// And so on...
// Easier/better composition
});
// How do we handle errors?
promiseA.then(function (resultA) {
promiseB.then(function (resultB) {
object.method(arg1, arg2, function (resultC) {
promiseC.then(function (resultC) {
promiseD.then(function (resultD) {
// And so on...
}).catch(function (error) {
// Handles promiseD errors only
});
}).catch(function (error) {
// Handles promiseC errors only
});
});
}).catch(function (error) {
// Handles promiseB errors only
});
}).catch(function (error) {
// Handles promiseA errors only
});
// Promise style
promiseA.then(function (resultA) {
return promiseB;
}).then(function (resultB) {
// Now returns a promise
return object.method(arg1, arg2);
}).then(function (resultC) {
return promiseD;
}).then(function (resultD) {
// And so on...
// Easier/better composition
}).catch(function (error) {
// Handles all errors at the end of the chain
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment