import { assert } from "../../assert.js";
import { AsynchronousAction } from "./AsynchronousAction.js";

export class PromiseAsynchronousAction extends AsynchronousAction {
    /**
     *
     * @param {function():Promise} factory
     */
    constructor(factory) {
        super();

        assert.isFunction(factory, 'factory');

        /**
         *
         * @type {function(): Promise}
         * @private
         */
        this.__factory = factory;
    }

    start() {
        super.start();

        let p;

        try {
            p = this.__factory();
        } catch (e) {
            this.__fail(e);
            return;
        }

        assert.defined(p, 'factory result');
        assert.notNull(p, 'factory result');
        assert.isObject(p, 'p');
        assert.isFunction(p.then, 'p.then');

        p.then(
            () => {
                this.__succeed();
            },
            (reason) => {
                this.__fail(reason);
            }
        );
    }
}
