Example uses of the SettingsManager library and Promiseifyish library
This page illustrates the general use of SettingsManager, as well as an example with a promiseified version, using Promiseifyish.
There are some advantages to using a promise-style API over standard callback style. In general, the code flows better and is easier to read with Promises.
Compare the two code samples below to see the difference between the callback style and the promise style.
Consider the typical use of the SettingsManager:
// Handlers
function onSettingsLoaded(settings) {
console.log('loaded', settings);
}
function onSettingsSaved() {
console.log('settings saved');
}
function onError(error) {
console.log('error:', error);
}
// Start with a load
var settingsManager = new SettingsManager();
settingsManager.load(function onLoad(settings) {
// Handle the load response and start a save
onSettingsLoaded(settings);
settingsManager.save({one: 1, two: 'two'}, function onSave() {
// Handle the save response and start another load
onSettingsSaved();
settingsManager.load(function onLoad(settings) {
// Handle the load response and start another save
onSettingsLoaded(settings);
settingsManager.save({three: 3, two: 2}, function onSave() {
// Handle the save response and start another load
onSettingsSaved();
settingsManager.load(function onLoad(settings) {
// Handle the load response
onSettingsLoaded(settings);
}, onError);
}, onError);
}, onError);
}, onError);
}, onError);
Compare with the promiseified version:
// Promiseify a SettingsManager instance
var promisifiedSettingsManager = Promiseify(new SettingsManager());
promisifiedSettingsManager.load()
.then(onSettingsLoaded)
.then(() => promisifiedSettingsManager.save({one: 1, two: 'two'}))
.then(onSettingsSaved)
.then(() => promisifiedSettingsManager.load())
.then(onSettingsLoaded)
.then(() => promisifiedSettingsManager.save({three: 3, two: 2}))
.then(onSettingsSaved)
.then(() => promisifiedSettingsManager.load())
.then(onSettingsLoaded)
.catch(onError);
This example shows code for both the standard usage as well as the promiseified usage, running next to each other. Notice how the results are the same; this shows that the promisiefied version retains API functionality.