How to pass internal function values as parameters to its callback

Viewed 50

Im sorry I don't know the exact wording so please bear with me. what Im trying to do is the same thing as we all do with the event listeners like so:

foo.addEventListener('click', function(event) {
    console.log(event.target)
})

with the example above I can access the event instance using the anonymous callback function. in my case, I have this simple function:

function post_rqst({ url, data = '', callback }) {
    let request = new XMLHttpRequest();
    request.open("POST", url, true);
    request.onload = function() {
        callback()
    }
    request.send(data)
}

now when I call the post_rqst(), I want to be able to access the request instance inside the callback definition like so:

post_rqst({
    url: 'foo.com/bar/',
    data: '[x,y,z]',
    callback: function(request) {
        if (request.status === 200) {
            console.log('done!')
        }
    }
})

Im a javascript newbie and I don't know what I don't know. thank you for your guidance in advance.

1 Answers

You can just pass that request instance when you call callback, so instead of:

function post_rqst({ url, data = '', callback }) {
    let request = new XMLHttpRequest();
    request.open("POST", url, true);
    request.onload = function() {
        callback();
    };
    request.send(data);
}

You would have:

function post_rqst({ url, data = '', callback }) {
    let request = new XMLHttpRequest();
    request.open("POST", url, true);
    request.onload = function() {
        callback(request);
    };
    request.send(data);
}

Here you can see that in action using setTimeout to fake that request:

function fakePost({ url, data = '', callback }) {
    const request = { url, data, method: 'POST' };
    
    setTimeout(() => {
      callback(request);
    }, 1000);
}

fakePost({
  url: 'https://stackoverflow.com/',
  data: 'foobar',
  origin: 'https://stackoverflow.com/',
  callback: (req) => {
    console.log('Callback received req =', req);
  },
});

Related