Kylin/Universal/Private/PromiseResolver.h
2024-09-15 23:39:23 +08:00

89 lines
1.8 KiB
C++

#ifndef __PROMISERESOLVER_H__
#define __PROMISERESOLVER_H__
template <typename T>
class Promise;
template <typename T>
class PromiseResolver {
public:
PromiseResolver(Promise<T> promise) : m_d{promise.m_d} {
}
template <typename V>
void resolve(V &&value) {
if (m_d) {
assert(m_d->isPending());
m_d->resolve(std::forward<V>(value));
m_d->dispatch();
}
}
void resolve() {
if (m_d) {
assert(m_d->isPending());
m_d->resolve();
m_d->dispatch();
}
}
template <typename E>
void reject(E &&error) {
if (m_d) {
assert(m_d->isPending());
m_d->reject(std::forward<E>(error));
m_d->dispatch();
}
}
void reject() {
if (m_d) {
assert(m_d->isPending());
m_d->reject(PromiseUndefinedException{});
m_d->dispatch();
}
}
private:
std::shared_ptr<PromiseData<T>> m_d;
};
template <typename T>
class PromiseResolve {
public:
PromiseResolve(PromiseResolver<T> resolver) : m_resolver{std::move(resolver)} {
}
template <typename V>
void operator()(V &&value) const {
m_resolver.resolve(std::forward<V>(value));
}
void operator()() const {
m_resolver.resolve();
}
private:
mutable PromiseResolver<T> m_resolver;
};
template <typename T>
class PromiseReject {
public:
PromiseReject(PromiseResolver<T> resolver) : m_resolver{std::move(resolver)} {
}
template <typename E>
void operator()(E &&error) const {
m_resolver.reject(std::forward<E>(error));
}
void operator()() const {
m_resolver.reject();
}
private:
mutable PromiseResolver<T> m_resolver;
};
#endif // __PROMISERESOLVER_H__