I\'m trying to create a constructor for a blogging platform and it has many async operations going on inside. These range from grabbing the posts from directories, parsing t
This is in typescript, but should be easily converted to ECMAscript
export class Cache {
private aPromise: Promise;
private bPromise: Promise;
constructor() {
this.aPromise = new Promise(...);
this.bPromise = new Promise(...);
}
public async saveFile: Promise {
const aObject = await this.aPromise;
// ...
}
}
The general pattern is to store the promises as internal variables using the constructor and await
for the promises in the methods and make the methods all return promises. This allows you to use async
/await
to avoid long promise chains.
The example I gave is good enough for short promises, but putting in something that requires a long promise chain will make this messy, so to avoid that create a private async
method that will be called by the constructor.
export class Cache {
private aPromise: Promise;
private bPromise: Promise;
constructor() {
this.aPromise = initAsync();
this.bPromise = new Promise(...);
}
public async saveFile: Promise {
const aObject = await this.aPromise;
// ...
}
private async initAsync() : Promise {
// ...
}
}
Here is a more fleshed out example for Ionic/Angular
import { Injectable } from "@angular/core";
import { DirectoryEntry, File } from "@ionic-native/file/ngx";
@Injectable({
providedIn: "root"
})
export class Cache {
private imageCacheDirectoryPromise: Promise;
private pdfCacheDirectoryPromise: Promise;
constructor(
private file: File
) {
this.imageCacheDirectoryPromise = this.initDirectoryEntry("image-cache");
this.pdfCacheDirectoryPromise = this.initDirectoryEntry("pdf-cache");
}
private async initDirectoryEntry(cacheDirectoryName: string): Promise {
const cacheDirectoryEntry = await this.resolveLocalFileSystemDirectory(this.file.cacheDirectory);
return this.file.getDirectory(cacheDirectoryEntry as DirectoryEntry, cacheDirectoryName, { create: true })
}
private async resolveLocalFileSystemDirectory(path: string): Promise {
const entry = await this.file.resolveLocalFilesystemUrl(path);
if (!entry.isDirectory) {
throw new Error(`${path} is not a directory`)
} else {
return entry as DirectoryEntry;
}
}
public async imageCacheDirectory() {
return this.imageCacheDirectoryPromise;
}
public async pdfCacheDirectory() {
return this.pdfCacheDirectoryPromise;
}
}