Map async result with automapper

前端 未结 3 527
夕颜
夕颜 2021-02-01 07:14

We are createing a Web.Api application of a angularjs application. The Web.Api returns a json result.

Step one was getting the data:

    public List

        
3条回答
  •  长情又很酷
    2021-02-01 07:44

    You can also add a couple of Task Extension Methods that will do this for you:

        public static Task Convert(this Task task)
        {
            if (task == null)
                throw new ArgumentNullException(nameof(task));
    
            var tcs = new TaskCompletionSource();
    
            task.ContinueWith(t => tcs.TrySetCanceled(), TaskContinuationOptions.OnlyOnCanceled);
            task.ContinueWith(t =>
            {
                tcs.TrySetResult(Mapper.Map(t.Result));
            }, TaskContinuationOptions.OnlyOnRanToCompletion);
            task.ContinueWith(t => tcs.TrySetException(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
    
            return tcs.Task;
        }
    
    
        public static Task> ConvertEach(this Task> task)
        {
            if (task == null)
                throw new ArgumentNullException(nameof(task));
    
            var tcs = new TaskCompletionSource>();
    
            task.ContinueWith(t => tcs.TrySetCanceled(), TaskContinuationOptions.OnlyOnCanceled);
            task.ContinueWith(t =>
            {
                tcs.TrySetResult(t.Result.Select(Mapper.Map).ToList());
            }, TaskContinuationOptions.OnlyOnRanToCompletion);
            task.ContinueWith(t => tcs.TrySetException(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
    
            return tcs.Task;
        }
    

提交回复
热议问题