Technically .. Yes, If the constructor returns a Promise
and as long as the await
is inside an async
function, here's an example ( might not be the best, actually it's a bad practice to have a constructor function return a Promise , but it's just to get this to work ):
class Test {
constructor() {
return new Promise((res, rej) => {
this.getData().then(({userId, title}) => {
this.userId = userId;
this.title = title;
res(this);
});
});
}
getData(){
return fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
}
greet(){
console.log('hello');
}
}
(async() => {
const x = await new Test();
console.log(x.userId, ' : ', x.title);
})();
await
is for asynchronous functions, and as far as I know constructors can't be asynchronous. Why exactly do you want to do this?await new Promise((ok, ko) => setTimeout(ok, 1000));
– although one would probably want to move thePromise
constructor call to a helper function. This is not covered by the “duplicates” at all, though.