0

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.

Khaos
  • 1
  • 1
    arrow functions `this` behaves differently, they can't be bound or `this` changed using call or apply ... `f3(function() {` may do what you expect – Jaromanda X Jan 17 '18 at 00:42
  • @Jaromanda X Thank you so much!! I've been trying to figure this out on and off for months and couldn't find the answer anywhere. My understanding of arrow functions was that they were just a different, shorter, and somehow optimized or better way of writing a function, and that if I switched to arrows, I wouldn't need to use function() anymore. Your answer works perfectly. Thank you so much. – Khaos Jan 17 '18 at 00:49

0 Answers0