Comparison of two different approaches to structuring code that uses Promises.
Version using .then()
, from Complex task dependencies:
files.getLastTwoVersions(filename)
.then(function(items) {
return [versions.get(items.last),
versions.get(items.previous)];
})
.spread(function(v1, v2) {
return diffService.compare(v1.blob, v2.blob)
})
.then(function(diff) {
// voila, diff is ready. Do something with it.
});
With wrapped functions (see below for the full source):
items = files.getLastTwoVersions(Promise.resolve(filename));
v1 = versions.get(items.get("last"));
v2 = versions.get(items.get("previous"));
diff = diffService.compare(v1.get("blob"), v2.get("blob"));
diff.then(function (s) {
// voila, diff is ready. Do something with it
});
Note that the only real difference between the wrapped functions and the imperative version is that in the wrapped functions version, you can't access properties "directly"--you need to use the .get()
method.
The function wrapping is accomplished by:
files.getLastTwoVersions = P(files.getLastTwoVersions);
(See below for P()
.)