public static void RegisterTask(this IJSValueConverterService target) { if (target.CanConvert <Task>()) { return; } //register internal call back types target.RegisterMethodConverter <string>(); target.RegisterFunctionConverter <JSValue>(); target.RegisterMethodConverter <JavaScriptValue>(); target.RegisterConverter <Task>( (node, value) => { var jsValueService = node.GetService <IJSValueService>(); var globalObject = jsValueService.JSGlobalObject; var converter = node.GetService <IJSValueConverterService>(); var tmp = node.WithContext(() => { JavaScriptValue.CreatePromise(out var result, out var resolve, out var reject); return(Tuple.Create(result, resolve, reject)); }); //start the task on new thread Task.Factory.StartNew(async() => { try { await value; jsValueService.CallFunction(tmp.Item2, globalObject); } catch (PromiseRejectedException ex) { var message = converter.ToJSValue(ex.ToString()); jsValueService.CallFunction(tmp.Item3, globalObject, message); } catch (Exception) { throw; } }); //return the promise without wait task complete return(tmp.Item1); }, (node, value) => { //from a promise return(Task.Factory.FromAsync( (callback, state) => { return BeginMethod(value, node, callback, state); } , EndMethod, null )); }, false ); }
public static void RegisterTask <TResult>(this IJSValueConverterService target) { if (target.CanConvert <Task <TResult> >()) { return; } //register internal call back types target.RegisterFunctionConverter <TResult>(); target.RegisterMethodConverter <TResult>(); target.RegisterMethodConverter <string>(); target.RegisterFunctionConverter <JSValue>(); target.RegisterMethodConverter <JavaScriptValue>(); target.RegisterMethodConverter <Action <TResult>, Action <JavaScriptValue> >(); target.RegisterConverter <Task <TResult> >( (node, value) => { //convert resolve, reject Action <Action <TResult>, Action <JavaScriptValue> > promiseBody = async(resolve, reject) => { try { var result = await value; resolve(result); } catch (PromiseRejectedException ex) { reject(ex.Error); } catch (Exception) { throw; } }; var jsValueService = node.GetService <IJSValueService>(); var globalObject = jsValueService.JSGlobalObject; var jsGlobalObject = new JSValue(node, globalObject); return(jsGlobalObject.CallFunction <Action <Action <TResult>, Action <JavaScriptValue> >, JavaScriptValue>("Promise", promiseBody, true)); }, (node, value) => { //from a promise return(Task.Factory.FromAsync( (callback, state) => { return BeginMethod <TResult>(value, node, callback, state); } , EndMethod <TResult>, null )); }, false ); }