summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibJS/Runtime/Promise.h
blob: 8ec2a8700073296f40875d1f1fa07a72bf2e6fc9 (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
63
64
65
66
67
68
/*
 * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

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

namespace JS {

ThrowCompletionOr<Object*> promise_resolve(VM&, Object& constructor, Value);

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

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

    static NonnullGCPtr<Promise> create(Realm&);

    virtual ~Promise() = default;

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

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

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

    bool is_handled() const { return m_is_handled; }
    void set_is_handled() { m_is_handled = true; }

protected:
    explicit Promise(Object& prototype);

    virtual void visit_edges(Visitor&) override;

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

    void trigger_reactions() const;

    // 27.2.6 Properties of Promise Instances, https://tc39.es/ecma262/#sec-properties-of-promise-instances
    State m_state { State::Pending };             // [[PromiseState]]
    Value m_result;                               // [[PromiseResult]]
    Vector<PromiseReaction*> m_fulfill_reactions; // [[PromiseFulfillReactions]]
    Vector<PromiseReaction*> m_reject_reactions;  // [[PromiseRejectReactions]]
    bool m_is_handled { false };                  // [[PromiseIsHandled]]
};

}