Last active
March 24, 2018 13:34
-
-
Save bryanjknight/907963b324fd241a747a7556ab2d6b99 to your computer and use it in GitHub Desktop.
Example of Promise chaining
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
'use strict'; | |
const Promise = require('bluebird'); | |
class Test { | |
constructor() { | |
this.count = 0; | |
} | |
doSomething() { | |
const self = this; | |
console.log("Doing something"); | |
return new Promise((resolve, reject) => { | |
self.count++; | |
setTimeout(resolve, 1000) | |
}); | |
} | |
doSomethingElse() { | |
const self = this; | |
console.log("Doing something else"); | |
return new Promise((resolve, reject) => { | |
self.count *= 2; | |
setTimeout(resolve, 1000) | |
}); | |
} | |
printCount() { | |
console.log("Final count: " + this.count); | |
} | |
run() { | |
this.doSomething() | |
.then(this.doSomethingElse.bind(this)) | |
.then(this.printCount.bind(this)) | |
.catch((err) => { | |
console.error(err); | |
}); | |
} | |
} | |
const t = new Test(); | |
t.run(); | |
// t.run() is async, so checking the count will give you a value | |
// at some point, but not the final answer | |
console.log("Random check on count: " + t.count); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment