public
Last active

Promise chaining example

  • Download Gist
example.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// `promise` is some operation that may succeed (fulfill) or fail (reject)
var newPromise = promise.then(
function () {
return delay(1000);
},
writeError
);
 
// If `promise` fulfills, `newPromise` will fulfill in 1000 ms.
// If `promise` rejects and writing to the error log succeeds,
// `newPromise` will fulfill: you transformed the rejection into fulfillment by handling it,
// similar to `try`/`catch`.
// If `promise` rejects and writing to the error log fails,
// `newPromise` will reject with the filesystem-related error: just as if
// code inside your `catch` block had thrown.
helpers.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// Writes to errors.log, returning a promise that will be fulfilled if the write succeeds
// or rejected if the write fails.
function writeError(errMessage) {
var deferred = Q.defer();
fs.writeFile("errors.log", errMessage, function (err) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve();
}
});
return deferred.promise;
}
 
// (or, using Q.nfcall:)
 
function writeError(errMessage) {
return Q.nfcall(fs.writeFile, "errors.log", errMessage);
}
 
// returns a promise that will be fulfilled in `ms` milliseconds
function delay(ms) {
var deferred = Q.defer();
setTimeout(deferred.resolve, ms);
return deferred.promise;
}

I think, now i got it. Great example.

simple and instructive

To be useful as an example it needs to be complete. This is incomplete since it provides no caller that uses the example functions, and a promise is not provided to which triggers "newPromise". So I disagree, this is bad example code IMHO.

@stefaneg -- agreed, this example isn't that great. Here's one that i made that introduces chaining in q. https://gist.github.com/jeffcogswell/8257755

Thanks @stefaneg. Your example helped out a lot. A combination of yours and the one that followed that shows how to pass args from promise to promise along with some rejection handling would be a perfect example.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.