Last active
May 25, 2018 10:17
-
-
Save domenic/2431341 to your computer and use it in GitHub Desktop.
Promise chaining example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// `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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
@imakedon, this might come a bit late, but the example clearly states this:
//
promise
is some operation that may succeed (fulfill) or fail (reject)
This means that the code is not 100% copy-paste and you should replace promise
with whatever asynchronous operation you have at your disposal.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Lame incomplete examples....
/promises.js:13
var newPromise = promise.then(
^
ReferenceError: promise is not defined
at Object. (/promises.js:13:18)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3