Skip to content

Instantly share code, notes, and snippets.

@tkissing
Created September 30, 2014 03:10
Show Gist options
  • Save tkissing/da645abfa7e9fa3bc9ea to your computer and use it in GitHub Desktop.
Save tkissing/da645abfa7e9fa3bc9ea to your computer and use it in GitHub Desktop.
Chain mandatory and optional async operations
// Problem:
// - We have 2 operations that can and should run in parallel
// - Both operations may finish in arbitrary order
// - one operation is mandatory, the other is optional
// - the result promise is to be resolved with a merge of the intermediate ones, with optional overriding mandatory
// Question:
// Can this be done
// - in a more readable manner than the "result = new Promise..." code block
// - with less code than the "result = new Promise..." code block
// See http://jsfiddle.net/tkissing/4nqhcb59/ http://jsfiddle.net/tkissing/4nqhcb59/1/ http://jsfiddle.net/tkissing/4nqhcb59/2/
var mandatory = new Promise(function (resolve, reject) {
function done() {
resolve({
a: 'mandatory', b: 'mandatory'
});
// or:
reject('Sorry');
}
setTimeout(done, 100 * Math.random());
});
var optional = new Promise(function (resolve, reject) {
function done() {
resolve({
b: 'optional'
});
// or:
reject('Sorry');
}
setTimeout(done, 100 * Math.random());
});
var result = new Promise(function (resolve, reject) {
return mandatory.then(function (obj) {
optional.then(function (extras) {
// optional worked => merge result into that of mandatory
Object.keys(extras).forEach(function (prop) {
obj[prop] = extras[prop];
});
resolve(obj);
}, function () {
// optional failed, just use result from mandatory
resolve(obj);
});
}, reject);
});
var print = function (txt, err) {
return function (obj) {
(console[err ? 'warn' : 'log'])(txt, obj, Date.now());
};
};
mandatory.then(print('mandatory'), print('mandatory', true));
optional.then(print('optional'), print('optional', true));
result.then(print('result'), print('result', true));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment