Last active
December 10, 2015 23:08
-
-
Save juandopazo/4506753 to your computer and use it in GitHub Desktop.
Issues with the current Y.Promise design when writing complex APIs based on promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This doesn't work due to some limitations in indexedDB | |
// It's just an example | |
// I'd like to be able to write: | |
Y.IndexedDB.open('mydb').store('myStore').put({ | |
foo: 'bar' | |
}); | |
/*************************** | |
Promise-based implementation | |
***************************/ | |
var indexedDB = Y.config.win.indexedDB; | |
Y.namespace('IndexedDB').open = function (name, version) { | |
return new IDBDatabase(function (resolver) { | |
var request = indexedDB.open(name, version); | |
request.onsuccess = function (e) { | |
resolver.fulfill(e.target.result); | |
}; | |
request.onfailure = function (err) { | |
resolver.reject(err); | |
}; | |
}); | |
}; | |
function IDBDatabase() { | |
IDBDatabase.superclass.constructor.apply(this, arguments); | |
} | |
Y.extend(IDBDatabase, Y.Promise, { | |
store: function (storeName) { | |
var promise = this; | |
// Notice how we're creating a promise here and there's two calls to `then` which means | |
// two more promises | |
return new IDBStore(function (fulfill, reject) { | |
promise.then(function (db) { | |
return db.transaction([storeName], "readwrite").objectStore(storeName); | |
}).then(fulfill, reject); | |
}); | |
} | |
}); | |
function IDBStore() { | |
IDBStore.superclass.constructor.apply(this, arguments); | |
} | |
Y.extend(IDBStore, Y.Promise, { | |
put: function (data) { | |
return this.then(function (store) { | |
return store.put(data); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I just realized I can ignore returning from that promise and avoid creating a third one: