c++ 简单模拟js Promise

发布时间 2023-09-21 09:40:43作者: laremehpe

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;
}