I'm very new to powershell. My question is very simple if you know anything about powershell.
In the code below I'm trying to fire an event from a piece of code running asynchronously as a job. For some reason, the code doesn't work.
$callback = {
param($event);
Write "IN CALLBACK";
};
$jobScript = {
while ($true) {
sleep -s 1;
"IN JOB SCRIPT";
New-Event myEvent;
}
}
Register-EngineEvent -SourceIdentifier myEvent -Action $callback;
Start-Job -Name Job -ScriptBlock $jobScript;
while ($true) {
sleep -s 1;
"IN LOOP";
}
Expected output:
IN LOOP
IN JOB SCRIPT
IN CALLBACK
IN LOOP
IN JOB SCRIPT
IN CALLBACK
...
Actual output:
IN LOOP
IN LOOP
IN LOOP
IN LOOP
...
After some reading, I changed this line
Start-Job -Name Job -ScriptBlock $jobScript
to
Start-Job -Name Job -ScriptBlock $jobScript | Wait-Job | Receive-Job;
and I get no output at all, because job never finishes.
It's kind of asynchoronous, but not really. It would be fairly simple to acomplish in JS.
const fireEvent = (eventName) => { ... }
const subscribeToEvent = (eventName, callback) => { ... }
const callback = () => console.log('IN CALLBACK')
subscribeToEvent('myEvent', callback);
setInterval(() => {
console.log('IN LOOP')
fireEvent('myEvent');
}, 1000)
Please, help!