Why this matters
Constructors are meant to initialize class instances synchronously. Including asynchronous operations can result in partially initialized objects and unexpected behavior. Use an explicit initialization method instead.
Ensure that constructors do not include asynchronous operations. Constructors should initialize class instances synchronously. If async logic is required, suggest moving it to a separate initialization method.
Constructors are meant to initialize class instances synchronously. Including asynchronous operations can result in partially initialized objects and unexpected behavior. Use an explicit initialization method instead.
Side-by-side examples engineers can pattern-match during review.
class MyClass {
constructor() {
Promise.resolve().then(() => this.data = fetchData()); // Noncompliant, this.data will be undefined in the new instance
}
}class MyClass {
constructor() {
this.data = null;
}
async initialize() {
this.data = await fetchData();
}
}
(async () => {
const myObject = new MyClass();
await myObject.initialize();
})();class MyClass {
constructor() {
Promise.resolve().then(() => this.data = fetchData()); // Noncompliant, this.data will be undefined in the new instance
}
}class MyClass {
constructor() {
this.data = null;
}
async initialize() {
this.data = await fetchData();
}
}
(async () => {
const myObject = new MyClass();
await myObject.initialize();
})();From the same buckets as this rule.
Check if loops use equality operators (== or !=) in termination conditions. These can lead to infinite loops if the condition is never met exactly. Instead, use relational operators like < or > for safer loop termination.