If you want to defer code execution until after the call stack has been emptied, consider using this approach:
return Promise.resolve().then(() => this._goIn = true);
class Task {
_name
_goIn
constructor(name) {
this._name = name;
this._goIn = false;
}
isGoIn() {
return this._goIn;
}
setGoIn() {
return Promise.resolve().then(() => this._goIn = true);
}
setName(name) {
return this._name = name;
}
}
// example
let task = new Task("test");
task.setGoIn().then(() => console.log("2. Asynchronous... it is now", task.isGoIn()));
console.log("1. Synchronous... it still remains", task.isGoIn());
You can also achieve the same with async
syntax:
async setGoIn() {
await null;
this._goIn = true;
}
class Task {
_name
_goIn
constructor(name) {
this._name = name;
this._goIn = false;
}
isGoIn() {
return this._goIn;
}
async setGoIn() {
await null;
this._goIn = true;
}
setName(name) {
return this._name = name;
}
}
// example
let task = new Task("test");
(async function() {
await task.setGoIn();
console.log("2. Asynchronous... it is now", task.isGoIn());
})(); // execute immediately
console.log("1. Synchronous... it still remains", task.isGoIn());
If you have access to queueMicroTask
or setTimeout
, then these are non-promise alternatives:
return setTimeout(() => this._goIn = true);
setTimout
returns the id of the timeout without indicating when the callback will be executed. queueMicroTask
returns undefined. Therefore, a Promise solution is generally preferred as it allows for easier chaining and usage within asynchronous contexts.