Answer the question
In order to leave comments, you need to log in
How can you implement in JS waiting for the execution of asynchronous tasks when describing a class?
Good day everyone.
The question is how would you solve the problem with a constructor and asynchronous processes.
Example:
class Name {
let self = this;
constructor(data){
this._init(data)
.then(data=>{
self.init = data;
})
.catch(console.error);
}
_init(data) {
return new Promise((resolve, reject) => {
// искусственно создаем задержку, эмцлируя веб запрос:
setTimeout(resolve, 2000, data);
//resolve(data);
})
run(data) {
rerurn data / this.init.
}
run2(data){
let self = this;
return new Promise((resolve, reject) => {
resolve(data / self.init);
})
}
}
let name = new Name(2);
console.log(name.run(6));
//или
name.run2(6).then(console.log).catch(console.error);
class Engine {
constructor(data) {
this.data = data;
}
static makeEngine(pathToData) {
return new Promise((resolve, reject) => {
getData(pathToData).then(data => {
resolve(new Engine(data))
}).catch(reject);
};
}
}
class Engine {
constructor(path) {
this.initialization = (async () => {
this.resultOfAsyncOp = await doSomethingAsync(path)
})()
}
async showPostsOnPage() {
await this.initialization
// actual body of the method
}
}
Answer the question
In order to leave comments, you need to log in
He asked, he answered ....
the reception is curious, but not without questions, is it worth it to do so. There are criticisms of using a constructor to perform initialization methods. But with asynchronous tasks, it seemed acceptable to me.
Open to new ideas.
class Name {
constructor(data) {
console.log('constructor start');
this.initialization = (async () => {
this.init = await this._init(data)
})();
console.log('constructor end');
}
_init(data){
return new Promise((resolve, reject)=>{
console.log('_init');
setTimeout(resolve, 2000, data);
});
}
async run(data) {
console.log('run start');
await this.initialization;
console.log('run end');
return data / this.init;
}
}
let name = new Name(2);
name.run(6).then(console.log).catch(console.error);
>node --harmony test2
constructor start
_init
constructor end
run start
run end
3
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question