Where to get the callback from the returned promise?
-
I tried to read all kinds of implementations many times, but they are still very difficult to understand.
Implementing my own version of promises, the idea is simple:
After executing the executor function, a callback is triggered, which executes resolve ().
The then method works like this
1) if the promise is resolved, then the callback is executed immediately inside then;
2) if the promise is not resolved, then the callback is saved, an empty promise is given. When the executor is executed, it will run the saved callback.
Question - sometimes the content of then makes a promise. How can I track the execution of this promise in order to catch the previous promise? Where to get the callback from?
'use strict' function MyPromise (fn) { this.executor_link = fn; this.state = 'pending'; this.value = null this.reject = function(error) { this.value = error; this.state = 'rejected'; if (this.saved_promise) { this.saved_err_callback(); this.saved_promise.reject(); } } this.resolve = function (val) { this.value = val; this.state = 'resolved'; if (this.saved_promise) { let got_promise = this.saved_ok_callback(this.value); if (got_promise) { console.log(got_promise); // откуда брать коллбек из этого промиса? Чтобы потом зарезолвить как в строке ниже } else { this.saved_promise.resolve(this.value); } } } this.then = function (ok_callback, err_callback) { if (this.state == 'pending') { this.saved_promise = new MyPromise(() => {}); this.saved_ok_callback = ok_callback; this.saved_err_callback = err_callback; return this.saved_promise } else if (this.state == 'rejected') { return new MyPromise(() => { err_callback(); this.reject(); }) } else { return new MyPromise(() => { ok_callback(this.value); }); } } let megares = this.resolve.bind(this); let megarej = this.reject.bind(this); try { fn(megares, megarej) } catch (catched_error) { this.reject(catched_error) } }
JavaScript Anonymous, Sep 26, 2020 -
If I understand your question and your code correctly, then I think you need to do something like this:
if (this.value instansOf MyPromise) {
return this.value.then(ok_callback, err_callback)
}Jack Valentine
1 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!