From f97660608a0df24cb1200ac7d9c6b19ccb4620e3 Mon Sep 17 00:00:00 2001 From: Determinant Date: Mon, 29 Jan 2018 17:52:05 -0500 Subject: use callback vector to avoid stack overflow --- promise.hpp | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/promise.hpp b/promise.hpp index 58b644f..397ef70 100644 --- a/promise.hpp +++ b/promise.hpp @@ -52,8 +52,10 @@ namespace promise { #define PROMISE_ERR_MISMATCH_TYPE do {throw std::runtime_error("mismatching promise value types");} while (0) class Promise { - function fulfilled_callback; - function rejected_callback; + //function fulfilled_callback; + //function rejected_callback; + std::vector> fulfilled_callbacks; + std::vector> rejected_callbacks; enum class State { Pending, Fulfilled, @@ -62,6 +64,8 @@ namespace promise { pm_any_t result; pm_any_t reason; + /* this implementation causes stack overflow because of the nested lambdas */ + /* void add_on_fulfilled(function cb) { auto old_cbs = fulfilled_callback; fulfilled_callback = function( @@ -79,6 +83,15 @@ namespace promise { cb(); }); } + */ + + void add_on_fulfilled(function cb) { + fulfilled_callbacks.push_back(cb); + } + + void add_on_rejected(function cb) { + rejected_callbacks.push_back(cb); + } function gen_on_fulfilled( function on_fulfilled, @@ -131,8 +144,10 @@ namespace promise { public: Promise(): + /* fulfilled_callback(do_nothing), rejected_callback(do_nothing), + */ state(State::Pending) { //printf("%lx constructed\n", (uintptr_t)this); } @@ -207,7 +222,8 @@ namespace promise { case State::Pending: result = _result; state = State::Fulfilled; - fulfilled_callback(); + //fulfilled_callback(); + for (const auto &cb: fulfilled_callbacks) cb(); break; default: break; @@ -220,7 +236,8 @@ namespace promise { case State::Pending: reason = _reason; state = State::Rejected; - rejected_callback(); + //rejected_callback(); + for (const auto &cb: rejected_callbacks) cb(); break; default: break; -- cgit v1.2.3-70-g09d2