随笔- 191  文章- 0  评论- 3  阅读- 59242 

main:

复制代码
#include <stdio.h>
#include "common.h"
#include "promise.h"
#include <chrono>   // std::chrono::seconds
#include <thread>   // std::this_thread::sleep_for


int main(void) {
    Promise* pro = new Promise([](call resolve, call reject) -> void {
        std::this_thread::sleep_for(std::chrono::seconds(3));
        resolve();
        });
    
    cout << "start " << endl;

    pro->then([]()->void {
        cout << "then1" << endl;
        })->then([]()->void {
            cout << "then2" << endl;
            });


    return 0;
}
复制代码

promise.h:

复制代码
#pragma once
#ifndef PROMISE
#define PROMISE 1

#include <string>
#include <iostream>
#include <functional>

using namespace std;

#define PROMISE_REJECTED 0
#define PROMISE_PENDING 1
#define PROMISE_FULLFILLED 2

//typedef void (*call)();
typedef function<void()> call;

class Promise
{
private:
    char state = 1; // 0->failed   1->pending   2->success
    string msg;
    void(*successCallback)();
    void(*failedCallback)();

public:
    Promise(void callable(call, call));
    Promise* resolve();
    Promise* reject();
    Promise* then(void(*cb)());
    Promise* error(void(*cb)());
};


#endif // !PROMISE
复制代码

promise.cpp:

复制代码
#include "promise.h"

Promise* Promise::resolve() {
    this->successCallback();
    this->state = PROMISE_FULLFILLED;
    return this;
}


Promise* Promise::reject() {
    this->failedCallback();
    this->state = PROMISE_REJECTED;
    return this;
}


Promise::Promise(void callable(call, call)) {
    this->state = PROMISE_PENDING;
    this->successCallback = []()->void {};
    this->failedCallback = []()->void {};
    try {
    callable([=]()->void {
        this->resolve();
        }, [=]()->void {
            this->reject();
        });
    }
    catch (bad_exception e) {
        this->reject();
    }

}

Promise* Promise::then(void(*cb)()) {
    if (this->state == PROMISE_FULLFILLED) {
        cb();
        return this;
    }
    this->successCallback = cb;
    return this;
}

Promise* Promise::error(void(*cb)()) {
    if (this->state == PROMISE_REJECTED) {
        cb();
        return this;
    }
    this->failedCallback = cb;
    return this;
}
复制代码

 

 posted on   laremehpe  阅读(62)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示