Answer the question
In order to leave comments, you need to log in
Where to get the callback from the returned promise?
Many times I tried to read all kinds of implementations, but they are still very difficult to understand.
I implement my version of promises, the idea is simple:
After executing the executor function, a callback is triggered that executes resolve().
The then method works like this
1) if the promise is resolved, then the callback inside then is executed immediately;
2) if the promise is not resolved, then the callback is saved, an empty promise is returned. When the executor is executed, it will run the saved callback.
Question - sometimes the content of then gives a promise. How to track the fulfillment of this promise in order to resolve the previous promise? Where to get callback?
'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)
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question