Callback Functions in TypeScript


#1

I’m just getting started with Angular 2 and TypeScript and I can’t seem to figure out how to use callback functions, I know this may be a silly question but given this regular javascript code: “An example of downloading such a photo”

downloadPhoto('http://coolcats.com/cat.gif', handlePhoto);

function handlePhoto (error, photo) {
  if (error) console.error('Download error!', error)
  else console.log('Download finished', photo)
}

console.log('Download started')


Here as we know three major things happen. First the handlePhoto function is declared, then the downloadPhoto function is invoked and passed the handlePhoto as its callback, and finally ‘Download started’ is printed out.

Note that the handlePhoto is not invoked yet, it is just created and passed as a callback into downloadPhoto. But it won’t run until downloadPhoto finishes doing its task, which could take a long time depending on how fast the Internet connection is.

What is the equivalent in TypeScript? :cold_sweat:

And Thanks in advance :slight_smile:


#2

The equivalent of this will be

downloadPhoto('http://coolcats.com/cat.gif', (error, photo)=>{
(error) ? console.error('Download error!', error) : console.log('Download finished', photo);
});
console.log('Download started')

I hope this helps your kung fu.


#3

My answer would be “as rarely as absolutely possible”. Most places you would be dealing with callback functions, such as many Cordova plugins, have already been converted by ionic-native to use Promises or Observables, which make for much more readable code than callbacks. If you are writing your own API, do similarly instead of expecting callbacks. If you are dealing with a source that you don’t control, and for which there is no existing asynchronous shim, I would recommend writing one so that none of the rest of your app code has to even think about callbacks.