首页 > 编程语言 >C#之Promise

C#之Promise

时间:2023-07-09 16:57:23浏览次数:32  
标签:return Thread C# res Promise new promise

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Interview.libs
{
    /// <summary>
    /// Promise状态
    /// </summary>
    enum PromiseStatus 
    {
        /// <summary>
        /// 准备好
        /// </summary>
        Pending = 0,
        /// <summary>
        /// 完成
        /// </summary>
        Fufilled = 1,
        /// <summary>
        /// 失败
        /// </summary>
        Faill = 2
    }

    /// <summary>
    /// 模拟JS的Promise
    /// </summary>
    public class Promise
    {
        public Promise(Action<Action<object>, Action<Exception>> init)
        {
            init(_Resolve, _Reject);
        }

        public static Promise Resolve(object data)
        {
            return new Promise((resolve, reject) =>
            {
                new Thread(() => {
                    Thread.Sleep(10);
                    resolve(data);
                }).Start();
            });
        }
        public static Promise Resolve(Promise promise)
        {
            return new Promise((resolve, reject) =>
            {
                promise.Then(res => {
                    resolve(res);
                    return res;
                });
            });
        }

        /// <summary>
        /// 当前promise的状态
        /// </summary>
        private PromiseStatus Status = PromiseStatus.Pending;
        /// <summary>
        /// 当前promise的数据 Object / Promise
        /// </summary>
        private object Data = default(object);
        /// <summary>
        /// 当前promise的错误
        /// </summary>
        private Exception Error = null;

        /// <summary>
        /// 当前promise 完成的处理韩式
        /// </summary>
        private List<Func<object, object>> ResolveList = new List<Func<object, object>>();
        /// <summary>
        /// 当前promise 失败的处理函数
        /// </summary>
        private List<Func<Exception, Exception>> RejectList = new List<Func<Exception, Exception>>();

        /// <summary>
        /// 成功的处理
        /// </summary>
        /// <param name="data"></param>
        private void _Resolve(object data)
        {
            Status = PromiseStatus.Fufilled;
            Data = data;
            ResolveList.ForEach(fn =>
            {
                Data = fn(Data);
            });
        }

        /// <summary>
        /// 失败的处理
        /// </summary>
        /// <param name="error"></param>
        private void _Reject(Exception error)
        {
            Status = PromiseStatus.Faill;
            Error = error;
            RejectList.ForEach(fn =>
            {
                Error = fn(Error);
            });
        }

        /// <summary>
        /// 链式调用的处理函数
        /// </summary>
        /// <param name="resole">成功处理</param>
        /// <param name="reject">失败处理</param>
        /// <returns></returns>
        public Promise Then(Func<object, object> resole, Func<Exception, Exception> reject = null)
        {
            if (resole != null)
            {
                if (Status == PromiseStatus.Fufilled)
                {
                    Data = Promise.Resolve(Data).Then(resole);
                }
                else
                {
                    ResolveList.Add(resole);
                }
            }
            if (reject != null)
            {
                if (Status == PromiseStatus.Fufilled)
                {
                    Error = reject(Error);
                }
                else
                {
                    RejectList.Add(reject);
                }
            }

            return this;
        }
    }
}

这个仅仅实现Promise基础部分,使用如下

 

 static void PromiseFn()
        {
            var promise = new Promise((resolve, reject) =>
            {
                Console.WriteLine("Promise: init");
                new Thread(() =>
                {
                    Thread.Sleep(5000);
                    Console.WriteLine("Promise: start");
                    resolve(1);
                }).Start();
            });

            promise.Then(res =>
            {
                Thread.Sleep(5000);
                Console.WriteLine("Promise: then1");
                return res + "2";
            }).Then(res =>
            {
                Thread.Sleep(5000);
                Console.WriteLine("Promise: then2");
                return Promise.Resolve(res + "*");
            }).Then(res =>
            {
                Thread.Sleep(5000);
                Console.WriteLine("Promise: then3");
                return res + "10";
            }).Then(res =>
            {
                Thread.Sleep(5000);
                Console.WriteLine("Promise: end:" + res);
                return res;
            });
        }

 

标签:return,Thread,C#,res,Promise,new,promise
From: https://www.cnblogs.com/ehuanrum/p/17538942.html

相关文章

  • C#之特性
    自定义自己的特性方法 MyCustom[AttributeUsage(AttributeTargets.Class|AttributeTargets.Field|AttributeTargets.Method,Inherited=true,AllowMultiple=true)]publicsealedclassMyCustomAttribute:Attribute{publicMyCustomAttribute()......
  • Cesium学习笔记3——加载地图服务
    申请成为天地图开发者,创建应用 编写代码:<!DOCTYPEhtml><htmllang="en"><head><!--Usecorrectcharacterset.--><metacharset="utf-8"/><!--TellIEtousethelatest,bestversion.--><......
  • 不用资源文件的 VC 窗口程序
    1.单个文件的windows VC程序,不用资源文件。在win32模板程序基础上改。2.菜单和热键的代码添加3.模式对话框的代码添加。 程序运行界面,最简的win32程序  代码如下,单个文件,比较麻烦的就是对话框。//NOT.cpp:////#include"stdafx.h"#include<windows.h>#......
  • Centos7中禁止root用户远程登录和修改登录端口
    Centos7中禁止root用户远程登录和修改登录端口介绍Linux中root用户权限比较大,被不法人员获知账户和密码后,用root登录后,可以对服务器做任何操作,对服务器危害较大,故需要禁止root用户登录,并且修改登录端口,这样就算root密码泄露,端口不是默认,也无法登录服务器禁止root用户1.修改......
  • 如何不加锁地将数据并发写入Apache Hudi?
    最近一位Hudi用户询问他们是否可以在不需要任何锁的情况下同时从多个写入端写入单个Hudi表。他们场景是一个不可变的工作负载。一般来说对于任何多写入端功能,Hudi建议启用锁定配置。但这是一个有趣的问题,我们进行探索并找到了解决方案,因此与更广泛的社区分享。需要并发写......
  • 1. Q_ CSS 属性是否区分大小写_
    Q:CSS属性是否区分大小写?```ul{MaRGin:10px;}```A:不区分。HTML,CSS都对大小写不敏感,但为了更好的可读性和团队协作一般都小写,而在XHTML中元素名称和属性是必须小写的。......
  • 5. Q_ 伪类选择器__checked_将作用与_input_类型为_radio_或者_check
    Q:伪类选择器:checked将作用与input类型为radio或者checkbox,不会作用于option。A:不对。伪类选择器checked的定义很明显:The:checkedCSSpseudo-classselectorrepresentsanyradio(<inputtype="radio">),checkbox(<inputtype="checkbox">)oroption(<opti......
  • lvgl PCwin系统codebook模拟
    转载地址:https://blog.csdn.net/qq_36347513/article/details/122837724一、LVGL简介LVGL(LightandVersatileGraphicsLibrary)轻量级通用型图形库,是一个免费的开源图形库,提供了创建嵌入式GUI所需的一切,具有易于使用的组件,美观的视觉效果和低内存占用等特点。支持触摸屏操作,......
  • [AGC036F] Square Constraints
    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa每个数能取的范围是一段区间\([l_i,r_i]\),其中\(l_i\)单调不增,\(r_i\)单调不增。画个图(\(n=10\)):圆环和矩形的交即为合法点。容易看出\(l_n\)到\(l_{2n-1}\)都是0。本质上是元素有上下界的排列计数,考虑不管下界......
  • AtCoder Beginner Contest 309
    A:1#include<cstdio>2#include<cstring>3#include<algorithm>4#include<iostream>5#include<string>6#include<vector>7#include<stack>8#include<bitset>9#include<cstdlib>10#include......