Reputation: 3637
I have a service that can only execute one command at a time. Normally this is fine because users of this service should await
the service calls and thus only one service call should begin at a time, however I can't guarantee this will always be the case. Instead, the service waits to finish its last call before it begins the next one. This is what I do in C#:
static async Task<string> Get(string url, params string[] parameters)
{
while(!isReady)
{
await Task.Yield();
}
// do stuff
}
I want to do a similar thing in an unrelated NodeJS project.
My Google-fu failed me. Is there a Javascript equivalent of C#'s Task.Yield()
that I can await
?
Upvotes: 1
Views: 389
Reputation: 3637
Ah, of course! It's simple. This might not be the best way but it works.
static async RunCommand(cmd: string, ...params: string[]): Promise<string> {
while(!this.isReady) {
await new Promise(resolve => setTimeout(resolve, 0));
}
// do stuff
}
Upvotes: 0
Reputation: 2824
You can use queueMicrotask()
for that.
queueMicrotask(() => {
// Code here will only run after the current thread have ended and all
// queued Promises have run until their next wait point or end.
});
In Node.js you can also use process.nextTick()
, which should behave the same as queueMicrotask
in most cases.
process.nextTick(() => {
// Deferred code goes here
})
Upvotes: 0
Reputation: 5827
I have a utility function called wait:
export const wait = (millis = 0) =>
new Promise(resolve => setTimeout(resolve, millis))
while(!isReady)
await wait()
Upvotes: 1