Skip to content

Instantly share code, notes, and snippets.

@thybzi
Created July 20, 2018 14:30
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 thybzi/dc7c4a8d214298c121d89864dbda80a3 to your computer and use it in GitHub Desktop.
Save thybzi/dc7c4a8d214298c121d89864dbda80a3 to your computer and use it in GitHub Desktop.
async/await & class
class Test {
constructor() {
this.processData({}).then((data) => {
console.log(data);
})
}
async processData(data) {
data = await this.one(data);
console.log('one');
data = await this.two(data);
console.log('two');
data = await this.three(data);
console.log('three');
return data;
}
one(data) {
return new Promise((resolve, reject) => {
setTimeout(() => {
data.foo = 11;
data.bar = 42;
resolve(data);
}, 2000);
});
}
two(data) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (data.hasOwnProperty('foo')) {
Object.keys(data).forEach((key) => {
data[key] = 2 * data[key];
});
resolve(data);
} else {
reject('wtf');
}
}, 500);
})
}
three(data) {
return new Promise((resolve, reject) => {
setTimeout(() => {
data.qux = Object.keys(data).reduce((result, key) => {
return result + data[key];
}, 0);
resolve(data);
}, 1000);
})
}
}
module.exports = new Test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment