summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibJS/Runtime/Promise.h
blob: c3adf9e249f3b46ae4fe92e681d4ce3ffe5d12e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
 * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/Vector.h>
#include <LibJS/Runtime/Object.h>

namespace JS {

Object* promise_resolve(GlobalObject&, Object& constructor, Value);

class Promise final : public Object {
    JS_OBJECT(Promise, Object);

public:
    enum class State {
        Pending,
        Fulfilled,
        Rejected,
    };
    enum class RejectionOperation {
        Reject,
        Handle,
    };

    static Promise* create(GlobalObject&);

    explicit Promise(Object& prototype);
    virtual ~Promise() = default;

    State state() const { return m_state; }
    Value result() const { return m_result; }

    struct ResolvingFunctions {
        Function& resolve;
        Function& reject;
    };
    ResolvingFunctions create_resolving_functions();

    Value fulfill(Value value);
    Value reject(Value reason);
    Value perform_then(Value on_fulfilled, Value on_rejected, Optional<PromiseCapability> result_capability);

private:
    virtual void visit_edges(Visitor&) override;

    bool is_settled() const { return m_state == State::Fulfilled || m_state == State::Rejected; }

    void trigger_reactions() const;

    State m_state { State::Pending };
    Value m_result;
    Vector<PromiseReaction*> m_fulfill_reactions;
    Vector<PromiseReaction*> m_reject_reactions;
    bool m_is_handled { false };
};

}