Arthur Miguel
Arthur Miguel

Reputation: 13

How can I use a callback function in typescript while using FileReader? Angular 5

I'm facing some difficults trying to apply promises/callbacks to my TypeScript function.

I need to gather reader.onloadend's result and send it to my nodejs express backend (using services), but the only way that I was able to do it was through setTimeout, and I'm pretty sure that if I can do it by using setTimeout, I can also do it by using promises/callbacks...

I just don't know how, I tried to pass callback as parameter and call it later, but I'm getting "callback is not a function".

var reader = new FileReader();
let inf = {}
let base64data;
let splitUrl = this.url.split('-')[4];    


reader.onloadend = function() {
  base64data = reader.result;

  inf = { base64: base64data, id: splitUrl }
}

setTimeout(() => {

  console.log(inf);
}, 3000);

Hey guys, I fixed it by changing from "function (){}" to an arrow function!

Upvotes: 0

Views: 774

Answers (1)

joh04667
joh04667

Reputation: 7437

Your callback function is called when the load has ended. Using setTimeout is a bad idea because it is completely decoupled with the load's asynchronous timing.

Just do what you want to do with the result in the callback.

reader.onloadend = () => {
  base64data = reader.result;

  inf = { base64: base64data, id: splitUrl }
  console.log(inf);
  doStuffWithFile(inf);
}

Upvotes: 1

Related Questions