I’m confused on the best practice method to write providers for async operations, and I need some help. Besides thinking of them as ways to persist data across pages, I consider them as ‘gateways’ to various external entities, such as firebase or http… therefore, I try to put all code that communicates externally into their own provider (i.e. firebase-auth, firebase-database, firebase-storage, etc)
Unfortunately, I suck at doing this.
My problem always comes up with how to manage and coordinate async operations between the provider and the page.
Here are some examples of some things I’ve played with:
- Promise wrapped in a promise method- In the provider I’ve written promises wrapped in promises, where the inside promise is the database/http/etc call, and the outside promise is the function that the calling page will use to coordinate async functions (using .then())
Example code in the provider.
public getPeople() {
return new Promise((resolve, reject) => {
this.storage.executeSql("SELECT * FROM people", []).then((data) =>
{
console.log(data);
resolve(people);
}, (error) => { reject(error); });
});
}
You would then kick off synchronous events in the calling page with .then() on the returned promise.
- Return a promise method- In the provider, the code is there just to set up the database/http/etc promise, that is just returned to the calling page where it uses .then() to coordinate operations.
Example code in the provider.
public getPeople() {
return this.storage.executeSql("SELECT * FROM people", [])
}
You would then kick off synchronous events in the calling page with .then() on the returned promise.
- EventEmitters method - All of the code for performing an async operations is written in the provider. The .then() is in the provider and passes the results back to the page via an event. The subscribe event, then, coordinates actions in the page itself.
Example code in the provider.
public getPeople() {
this.storage.executeSql("SELECT * FROM people", []).then((data) =>
{
this.events.publish('getPeople', data);
}
}
You would then kick off synchronous events in the calling page by subscribing to the event emitter.
I like the emitter method… but I rarely, if ever see it used in tutorials or in github. Typically, I see the first method… but it seems odd to write a promise inside of another promise.
What method do you use? Is there better way to do this?
