I have a function (f3
) that initiates a string of events, right now only calling f2
and passing down its callback to be called when the string of events ends. My function, f1
, is a promise that returns an object, which is taken in by the .then()
of the promise and I have verified with console.log
that that's working up to that point and firing in the correct order. Immediately after, I call the callback function from inside that same scope with .call(obj)
attached, but when I log what the value of this
is inside the callback, it returns {}
instead of the value of obj
.
// promise that defines object and passes it to next function
function f1() {
return new Promise((resolve, reject) => {
var obj = {
key1: "info",
key2: "more info",
etc: "and on and on..."
};
resolve(obj);
});
}
// calls f1 and calls callback of f3 with new data from then of f1
function f2(cb) {
f1().then((obj) => {
console.log(obj); // Outputs actual values in obj as defined in f1
cb.call(obj); // Successfully calls function, but "this" is not replaced with "obj" in callback
})
}
// overarching function that initiates chain of events
function f3(cb) {
f2(cb);
};
f3(() => {
console.log(this); // Outputs an empty object
});
I cannot for the life of me figure out what's preventing .call()
, or .bind()
, which I've also tried, from altering the this object in my callback. Please help me understand what I'm doing wrong.