[Ionic 4] Doubt regarding an asynchronous function and how I should correctly run it synchronously

Imperative and reactive programming are very different mindsets, so attempting to write an Ionic application in an imperative style is going to result in no end of frustration.

Here is a taxonomy I use when writing asynchronous code. I would consider uriToBase64 a “category C” function - we care about what it returns and when, therefore any time we call it, two things about the calling context should be true:

  • from a function whose return type is also a future
  • the first word of which is return

Although those rules may seem arbitrary and capricious, they save us from doomed imperative algorithms. Instead of “loop through user’s local images, doing stuff to each one”, I would suggest thinking in terms of feeding a reactive pipeline:

localFiles(): Promise<string[]> {
  // resolve to a list of things that `imageFilePath` loops across in current code
}

Since uriToBase64 maps one path to a base64 string, we can apply that operation to our pipeline:

localBase64s(): Promise<string[]> {
  return this.localFiles().then(paths => paths.map(path => this.uriToBase64(path)));
}

…and we can continue bubbling that up to create the zip file:

this.localBase64s().then(b64s => {
  // build zip in here and return the completed zip
});
1 Like