Skip to content

Instantly share code, notes, and snippets.

@ststeiger
Created September 9, 2024 17:06
Show Gist options
  • Save ststeiger/a880789b38b66672c4651ef3188abbca to your computer and use it in GitHub Desktop.
Save ststeiger/a880789b38b66672c4651ef3188abbca to your computer and use it in GitHub Desktop.
Syntax Comparison Promises with C# and JavaScript
namespace BaristaLabs.SkinnyHtml2Pdf.Web
{
/*
function waitForEvent()
{
return new Promise((resolve, reject) =>
{
try
{
// Simulate event success after 1 second
setTimeout(() => resolve("Event succeeded"), 1000);
}
catch (error)
{
reject(error);
}
});
}
function without_async()
{
waitForEvent()
.then(result => console.log(result)) // Event succeeded
.catch(error => console.error(error));
}
async function withAsync()
{
try
{
let msg = await waitForEvent();
console.log(msg);
}
catch (err)
{
console.log(err);
}
}
*/
public class ChromeSessionExample
{
public delegate System.Threading.Tasks.Task<int> SomeCallback_t(int abc);
private static void MakeAjaxCall(SomeCallback_t callback)
{
callback(3);
}
public static async System.Threading.Tasks.Task<int> MakeAjaxCallAsync()
{
// TaskCompletionSource to signal the event completion or failure
System.Threading.Tasks.TaskCompletionSource<int> tcs = new System.Threading.Tasks.TaskCompletionSource<int>();
MakeAjaxCall(
async delegate (int abc)
{
try
{
await System.Threading.Tasks.Task.Delay(2000);
// If everything goes well, complete the task successfully
tcs.SetResult(100/abc);
}
catch (System.Exception ex)
{
// If an error occurs, set the task's exception to propagate it
tcs.SetException(ex);
}
return 666;
}
);
int a = await tcs.Task;
return a;
}
public static async System.Threading.Tasks.Task<bool> WaitForPageNavigationAsync(BaristaLabs.ChromeDevTools.Runtime.ChromeSession session)
{
// TaskCompletionSource to signal the event completion or failure
System.Threading.Tasks.TaskCompletionSource<bool> tcs = new System.Threading.Tasks.TaskCompletionSource<bool>();
// Subscribe to the FrameNavigated event
session.Page.SubscribeToFrameNavigatedEvent(
delegate (BaristaLabs.ChromeDevTools.Runtime.Page.FrameNavigatedEvent e)
{
try
{
// Event processing logic here
System.Console.WriteLine($"Navigated to {e.Frame.Url}");
// If everything goes well, complete the task successfully
tcs.SetResult(true);
}
catch (System.Exception ex)
{
// If an error occurs, set the task's exception to propagate it
tcs.SetException(ex);
}
tcs.SetResult(true);
}
);
// Await the task (it will either complete successfully or throw an error)
return await tcs.Task;
}
public static async System.Threading.Tasks.Task Test(BaristaLabs.ChromeDevTools.Runtime.ChromeSession session)
{
bool x = await WaitForPageNavigationAsync(session);
System.Console.WriteLine(x);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment