|
| 1 | +<# |
| 2 | +.SYNOPSIS |
| 3 | + awaits asynchronous operations |
| 4 | +.DESCRIPTION |
| 5 | + awaits the result of a task. |
| 6 | +.EXAMPLE |
| 7 | + .>PipeScript -ScriptBlock { |
| 8 | + await $Websocket.SendAsync($SendSegment, 'Binary', $true, [Threading.CancellationToken]::new($false)) |
| 9 | + } |
| 10 | +.EXAMPLE |
| 11 | + .>PipeScript -ScriptBlock { |
| 12 | + $receiveResult = await $Websocket.ReceiveAsync($receiveSegment, [Threading.CancellationToken]::new($false)) |
| 13 | + } |
| 14 | +#> |
| 15 | +[ValidateScript({ |
| 16 | + $CommandAst = $_ |
| 17 | + $CommandAst.CommandElements -and $CommandAst.CommandElements[0].Value -eq 'await' |
| 18 | +})] |
| 19 | +param( |
| 20 | +[Parameter(Mandatory,ValueFromPipeline)] |
| 21 | +[Management.Automation.Language.CommandAST] |
| 22 | +$CommandAst |
| 23 | +) |
| 24 | + |
| 25 | +process { |
| 26 | + if ($CommandAst.CommandElements.Count -lt 2) { |
| 27 | + Write-Error "await what?" |
| 28 | + return |
| 29 | + } |
| 30 | + |
| 31 | + if ($CommandAst.CommandElements[0].Value -ne 'await') { |
| 32 | + Write-Error "not await" |
| 33 | + return |
| 34 | + } |
| 35 | + |
| 36 | + if ($CommandAst.CommandElements[1] -isnot [Management.Automation.Language.InvokeMemberExpressionAst]) { |
| 37 | + Write-Error "await must be followed by an invocation expression" |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + # Note: This is one of those cases where version targeting might be handy. |
| 42 | + # older versions of PowerShell (I believe -lt 4.0) will not handle task returns correctly without help. |
| 43 | + |
| 44 | + [Timespan]$awaitTimeout = '00:00:10' |
| 45 | + [Timespan]$awaitSleep = 7 |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | + $newScript = @( |
| 50 | + '[DateTime]$awaitTimeout = [DateTime]::Now + "' + "$awaitTimeout" + '"' |
| 51 | + '[TimeSpan]$awaitSleep = "' + "$awaitSleep" + '"' |
| 52 | + '$awaitTask = ' + "$($commandAst.CommandElements[1].Extent.ToString())" |
| 53 | +{ |
| 54 | +while (!$awaitTask.IsCompleted -and [DateTime]::Now -lt $awaitTimeout) { |
| 55 | + Start-Sleep -Milliseconds $awaitSleep.TotalMilliseconds |
| 56 | +} |
| 57 | +if ($awaitTask.IsCompleted -and $null -ne $awaitTask.Result) { |
| 58 | + $awaitTask.Result |
| 59 | +} |
| 60 | +elseif ($awaitTask.IsCompleted -and $awaitTask.Exception) { |
| 61 | + if ($awaitTask.Exception.InnerExceptions) { |
| 62 | + $awaitTask.Exception.InnerExceptions |
| 63 | + } else { |
| 64 | + $awaitTask.Exception |
| 65 | + } |
| 66 | +} |
| 67 | +} |
| 68 | + |
| 69 | + ) -join [Environment]::NewLine |
| 70 | + |
| 71 | + if ($CommandAst.IsAssigned) { |
| 72 | + $newScript = "`$($newScript)" |
| 73 | + } |
| 74 | + |
| 75 | + [ScriptBlock]::create($newScript) |
| 76 | +} |
0 commit comments