Created
July 20, 2018 14:30
async/await & class
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
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