import { getDeferred } from '@f2/defer';
export class Promisify {
    _onfulfilledFns = [];
    _onrejectedFns = [];
    resolved;
    rejected;
    resolve(value) {
        this.resolved = {
            value
        };
        this._onfulfilledFns.forEach(cb => cb(value));
    }
    reject(err) {
        this.rejected = {
            err: err
        };
        this._onrejectedFns.forEach(cb => cb(err));
    }
    then(onfulfilled, onrejected) {
        const deferred = getDeferred();
        if (onfulfilled) {
            const _onfulfilled = async (v) => {
                try {
                    const r = await onfulfilled(v);
                    deferred.resolve(r);
                }
                catch (err) {
                    deferred.reject(err);
                }
            };
            if (this.resolved) {
                _onfulfilled(this.resolved.value);
            }
            else {
                this._onfulfilledFns.push(_onfulfilled);
            }
        }
        if (onrejected) {
            this._catch(deferred, onrejected);
        }
        return deferred.promise;
    }
    _catch(deferred, onrejected) {
        const _onrejected = async (err) => {
            try {
                const r = await onrejected(err);
                deferred.resolve(r);
            }
            catch (err) {
                deferred.reject(err);
            }
        };
        if (this.rejected) {
            _onrejected(this.rejected.err);
        }
        else {
            this._onrejectedFns.push(_onrejected);
        }
        return deferred.promise;
    }
    catch(onrejected) {
        const deferred = getDeferred();
        this._catch(deferred, onrejected);
        return deferred.promise;
    }
}
