Skip to content

Instantly share code, notes, and snippets.

@tmilos
Last active May 31, 2016 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmilos/cfde792fe11e90f7e3841ef39c0b9e3c to your computer and use it in GitHub Desktop.
Save tmilos/cfde792fe11e90f7e3841ef39c0b9e3c to your computer and use it in GitHub Desktop.
NodeJS Promises
"use strict";
const Promise = require('bluebird')
class MyAction {
constructor (name, nextAction, preFail, postFail) {
this.name = name
this.nextAction = nextAction
this.preFail = preFail
this.postFail = postFail
}
execute (context) {
return Promise.bind(this)
.then(function () {
console.log(this.name+' pre')
if (this.preFail) {
throw new Error(this.name+' pre')
}
})
.then(function () {
console.log(this.name+' mid')
if (this.nextAction) {
return this.nextAction.execute(context)
}
})
.then(function () {
console.log(this.name+' post')
if (this.postFail) {
throw new Error(this.name+' post')
}
})
.catch(function (e) {
console.log(this.name+' error:', e)
throw e
})
} // execute
} // class
let a3 = new MyAction('treci', null, true, false);
let a2 = new MyAction('drugi', a3, false, false);
let a1 = new MyAction('prvi', a2, false, false);
a1.execute({})
.catch(function (e) {
console.log('TOP error', e, e.stack)
})
prvi pre
prvi mid
drugi pre
drugi mid
treci pre
treci error: [Error: treci pre]
drugi error: [Error: treci pre]
prvi error: [Error: treci pre]
TOP error [Error: treci pre] Error: treci pre
at MyAction.<anonymous> (d:\www\home\tmilos\nodejs_action_test\promise.js:19:15)
at MyAction.tryCatcher (d:\www\home\tmilos\nodejs_action_test\node_modules\bluebird\js\release\util.js:16:23)
at Promise._settlePromiseFromHandler (d:\www\home\tmilos\nodejs_action_test\node_modules\bluebird\js\release\promise.js:502:31)
at Promise._settlePromise (d:\www\home\tmilos\nodejs_action_test\node_modules\bluebird\js\release\promise.js:559:18)
at Promise._settlePromiseCtx (d:\www\home\tmilos\nodejs_action_test\node_modules\bluebird\js\release\promise.js:596:10)
at Async._drainQueue (d:\www\home\tmilos\nodejs_action_test\node_modules\bluebird\js\release\async.js:143:12)
at Async._drainQueues (d:\www\home\tmilos\nodejs_action_test\node_modules\bluebird\js\release\async.js:148:10)
at Immediate.Async.drainQueues [as _onImmediate] (d:\www\home\tmilos\nodejs_action_test\node_modules\bluebird\js\release\async.js:17:14)
at processImmediate [as _immediateCallback] (timers.js:383:17)
{
"name": "nodejs_promise_test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bluebird": "^3.4.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment