Skip to content

Instantly share code, notes, and snippets.

@bryanjknight
Last active March 24, 2018 13:34
Show Gist options
  • Save bryanjknight/907963b324fd241a747a7556ab2d6b99 to your computer and use it in GitHub Desktop.
Save bryanjknight/907963b324fd241a747a7556ab2d6b99 to your computer and use it in GitHub Desktop.
Example of Promise chaining
'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