How to Get Progress from Xmlhttprequest

How to show Progress in XMLHttpRequest

You can add Event Listeners to your xmlHttpRequest.

MDN has a very good documentation on this.

Monitoring progress

XMLHttpRequest Progress Events within a Promise

Unfortunately base promises don't have a way of representing any kind of progress. They are only pass/fail and can only send one result. You can think of them more as a delayed function return rather than a callback. You will probably need to accept a progress callback from your function and send that information out an alternate route. If you use a promise library some of them do have a progress callback option (ex. https://github.com/kriskowal/q search for "Progress Notification")

How to get XMLHttpRequest Promise progress

Promises are simply not a good architectural match for multiple progress notifications. Promises are a one-way state machine meant to communicate completion or error - that's really all they are designed for. They do not have any mechanism built-in for doing multiple progress notifications.

Instead, for progress notifications, you should some other architectural mechanism such as a regular callback that is called each time or an eventEmitter that triggers multiple progress events.

In the scheme you've shown so far, it would probably look like this:

var callback = {
success: function(data){...},
failure: function(data){...},
progress: function(data){...}
}

Test(token).download(url, callback.progress).then(callback.success, callback.failure);

Then, inside your download() function, you call the progress callback as many times as appropriate.


Personally, I think it would be more useful to your callers if you just returned the promise and let them supply resolve and reject handlers themselves rather than hiding the promise and making your callers live with the year 2013 callback architecture. Returning the promise allows them to use all the promise features such as chaining, aggregation with other promises, error propagation in their own code, etc...

So rather than passing in a callback object with multiple callbacks, all they pass in is the progress callback and you return back a promise. The caller can then attach their own resolve and reject handlers on the returned promise. It's 2016 and promises are standardized in ES6. There's no need to hide them from your callers and there's every reason to return the promise so your callers can tap into the benefits of promises too.



Related Topics



Leave a reply



Submit