I have the following class in Typescript (using the Aurelia SPA-framework).
import { inject } from "aurelia-framework";
import {Apiclient} from "../services/apiclient";
import * as gravatarUrl from "gravatar-url";
// Dialogs
import {DialogService} from "aurelia-dialog";
import {RedigerBruker} from "./dialogs/rediger-bruker";
@inject(Apiclient, DialogService)
export class Brukere {
users;
lastFetchSuccess:boolean = true;
constructor(private api:Apiclient, private dialog:DialogService) {
}
gravatar(email) {
return gravatarUrl(email, { size: 48, default: "mm" });
}
activate() {
return this.api.getUsers().then(
res => {
if(res.status == 200) {
res.resultObject.then(json => this.users = json);
this.lastFetchSuccess = true;
} else {
this.lastFetchSuccess = false;
};
});
}
editUser(userId) {
this.api.getUser(userId).then(
res => {
if(res.status == 200) {
res.resultObject.then(json => {
this.dialog.open({ viewModel: RedigerBruker, model: json })
.then(response => {
if (!response.wasCancelled) {
console.log("MKS: Good - " + response.output);
} else {
console.log("MKS: Bad");
}
});
});
} else {
console.log(`MKS: Error retrieving user ${userId}: ${res.status} - ${res.statusText}`);
}
});
}
}
This code works. The API-client is just a simple wrapper around the fetch-client that returns simplified objects with status, statustext and the JSON-result promise. If you look at the editUser
function. This function takes a user-id, passes it to the api-client which fetches the data from the server, and then returns the result-object. This code looks like the usual callback-pyramid-of-doom. Which makes me think I'm not using promises correctly.
Am I completely fumbling the use of promises, or is this just the way it works and I have to deal with it? Maybe there is some other way to code this?