Map async result with automapper

前端 未结 3 521
夕颜
夕颜 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:52

    Jose's solution proved quite useful to me. I did, however, re-target the extension method to extend IMapper which allowed me to remove the singleton Mapper reference.

    public static class MapperExtensions
    {
        public static Task MapAsync(this IMapper mapper, 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;
        }
    }
    

提交回复
热议问题