PendingResponse.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Heap/Heap.h>
  7. #include <LibJS/Runtime/VM.h>
  8. #include <LibWeb/Fetch/Fetching/PendingResponse.h>
  9. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  10. #include <LibWeb/Platform/EventLoopPlugin.h>
  11. namespace Web::Fetch::Fetching {
  12. JS::NonnullGCPtr<PendingResponse> PendingResponse::create(JS::VM& vm, JS::NonnullGCPtr<Infrastructure::Request> request)
  13. {
  14. return vm.heap().allocate_without_realm<PendingResponse>(request);
  15. }
  16. JS::NonnullGCPtr<PendingResponse> PendingResponse::create(JS::VM& vm, JS::NonnullGCPtr<Infrastructure::Request> request, JS::NonnullGCPtr<Infrastructure::Response> response)
  17. {
  18. return vm.heap().allocate_without_realm<PendingResponse>(request, response);
  19. }
  20. PendingResponse::PendingResponse(JS::NonnullGCPtr<Infrastructure::Request> request, JS::GCPtr<Infrastructure::Response> response)
  21. : m_request(request)
  22. , m_response(response)
  23. {
  24. m_request->add_pending_response({}, *this);
  25. }
  26. void PendingResponse::visit_edges(JS::Cell::Visitor& visitor)
  27. {
  28. Base::visit_edges(visitor);
  29. visitor.visit(m_request);
  30. visitor.visit(m_response);
  31. }
  32. void PendingResponse::when_loaded(Callback callback)
  33. {
  34. VERIFY(!m_callback);
  35. m_callback = move(callback);
  36. if (m_response)
  37. run_callback();
  38. }
  39. void PendingResponse::resolve(JS::NonnullGCPtr<Infrastructure::Response> response)
  40. {
  41. VERIFY(!m_response);
  42. m_response = response;
  43. if (m_callback)
  44. run_callback();
  45. }
  46. void PendingResponse::run_callback()
  47. {
  48. VERIFY(m_callback);
  49. VERIFY(m_response);
  50. Platform::EventLoopPlugin::the().deferred_invoke([strong_this = JS::make_handle(*this)] {
  51. strong_this->m_callback(*strong_this->m_response);
  52. strong_this->m_request->remove_pending_response({}, *strong_this.ptr());
  53. });
  54. }
  55. }