I am struggling to wrap my head around chaining together promises to achieve a desired result.
Brief background: I'm Using Ionic2 (based on Angular2) to create mobile app. Data persistence is based on SQLite. In order to re-build a complex object that contains nested arrays, I need to chain together a number of database calls.
buildObjectFromID(id) {
return new Promise(function (resolve, reject) {
let db = new DBHelper();
try {
// Get the event object from id
db.getEventWithCMSID(id).then(event => {
db.getBannerForOwner(event.cmsId).then(banner => {
event.banner = banner;
});
db.getImagesForOwner(event.cmsId).then(images => {
event.images = images;
});
db.getProfilePicturesForOwner(event.cmsId).then(profilepictures => {
event.profilepicture = profilepictures;
});
db.getLogosForOwner(event.cmsId).then(logos => {
event.logos = logos;
});
resolve(event);
});
}
catch
(err) {
reject({err: err});
}
}
);
}
This method aims to fetch a main object from the database, and using it's ID, fetches and appends its related properties from additional tables. I wish to rebuild the object in it's entirety before passing the result back.
However, at the moment, the object is passed back and then over time the properties are added once each additional call is completed.
I would really appreciate if someone could inform me how I can chain these together, so that the controller calling 'buildObjectFromID' gets a complete object.
Many thanks.